How can I read a file as unsigned bytes in Java?

前端 未结 5 1224
名媛妹妹
名媛妹妹 2021-01-12 14:39

How can I read a file to bytes in Java?

It is important to note that all the bytes need to be positive, i.e. the negative range cannot be used.

Can this be d

5条回答
  •  借酒劲吻你
    2021-01-12 15:22

    If using a larger integer type internally is not a problem, just go with the easy solution, and add 128 to all integers before multiplying them. Instead of -128 to 127, you get 0 to 255. Addition is not difficult ;)

    Also, remember that the arithmetic and bitwise operators in Java only returns integers, so:

    byte a = 0;
    byte b = 1;
    
    byte c = a | b;
    

    would give a compile time error since a | b returns an integer. You would have to to

    byte c = (byte) a | b;
    

    So I would suggest just adding 128 to all your numbers before you multiply them.

提交回复
热议问题