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...
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 0
to 255
, 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):
00000000000000000000000011111101
If you do:
int i = 253;
byte b = (byte) i;
then b
will contain the bits:
11111101
If you ask Java to use this, Java will claim it is -3
because when interpreting bits as signed, -3
is represented as the pattern 11111101
. And so if you write that byte to a file, the bits 11111101
will 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 11111101
which, again, Java will interpret as -3
. So you cannot just do:
byte b = readByteFromFile();
int i = b;
because Java will interpret b
's contents as -3
and give you the integer that represents -3
as a 32-bit integer, which will be:
11111111111111111111111111111101
Instead, you need to mask things off to make sure the integer you end up with is:
00000000000000000000000011111101
So,
byte b = readByteFromFile();
int i = (0x000000FF) & b;
DataOutputStream.writeByte()
will write the int
as a 1-byte value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With