I need convert integer
to byte
and write byte in file but when i convert a number larger than 128 to byte in convert to a negative number.
I need to use unsigned char but i don't know how.
in c++ we write unsigned
but how is it in java?

- 14,205
- 26
- 82
- 117
-
Java doesn't have `unsigned`. Could you be more specific about what you're trying to do, and the results you're getting? – David Thornley Jun 23 '11 at 20:01
3 Answers
Java doesn't have unsigned
types by default but you can workaround it, see Java and unsigned int, unsigned short, unsigned byte, unsigned long, etc. (Or rather, the lack thereof)

- 46,010
- 9
- 86
- 95
Java doesn't have unsigned types. I suggest you use a short, since it can accommodate all the values available to an unsigned char in languages like C and C++.
You might find this question interesting.

- 1
- 1

- 9,299
- 2
- 28
- 35
Writing bytes is not a problem, it doesn't matter whether you use write(int)
or writeByte(byte)
since the data written is still the same whether the byte is signed or unsigned. Reading bytes using read()
also isn't a problem, because it returns unsigned bytes. Only when you're reading into a byte array do you need to be careful, because then you have to remember to mask each byte with 0xFF
when you use it.

- 54,642
- 8
- 60
- 72
-
This will generally work, unless you happen to be processing data which came from (or is going to) a system with different endian-ness – Edwin Buck Jun 23 '11 at 20:18