In java, how do I write integers to a file so that they are unsigned 8 bit integers (within range 0 to 255) ? Is it enough that the numbers are of type int and within 0-255, or do I need to convert them to some other type first? I think it’s just the same thing? But I’m not sure if something funny happens when they get placed in the file…
Share
Signed vs. unsigned is only a matter of how the bit patterns are interpreted, not the bit patterns themselves.
So if as long as your integers are in the range
0to255, you can just jam them into bytes and write the bytes to a file.However, because Java interprets byte bit patterns as being signed, you have to be careful when reading them back in.
For example, say you have the integer
253. This is (in full 32-bit form):If you do:
then
bwill contain the bits:If you ask Java to use this, Java will claim it is
-3because when interpreting bits as signed,-3is represented as the pattern11111101. And so if you write that byte to a file, the bits11111101will be written out, as desired.Likewise, when you read it back in to a byte when reading the file, the byte you read it into will be filled with the bit pattern
11111101which, again, Java will interpret as-3. So you cannot just do:because Java will interpret
b‘s contents as-3and give you the integer that represents-3as a 32-bit integer, which will be:Instead, you need to mask things off to make sure the integer you end up with is:
So,