0

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?

Mahdi_Nine
  • 14,205
  • 26
  • 82
  • 117

3 Answers3

5

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)

ismail
  • 46,010
  • 9
  • 86
  • 95
2

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.

Community
  • 1
  • 1
Martin Törnwall
  • 9,299
  • 2
  • 28
  • 35
1

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.

Neil
  • 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