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
  • 13,285
  • 26
  • 79
  • 116

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
  • 43,610
  • 8
  • 84
  • 94
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
  • 8,889
  • 2
  • 27
  • 33
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
  • 52,766
  • 8
  • 57
  • 71
  • 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