Mahdi_Nine
Mahdi_Nine

Reputation: 14751

how can i use unsigned in java

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?

Upvotes: 0

Views: 253

Answers (3)

Neil
Neil

Reputation: 55382

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.

Upvotes: 1

ismail
ismail

Reputation: 47572

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)

Upvotes: 5

Martin Törnwall
Martin Törnwall

Reputation: 9599

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.

Upvotes: 2

Related Questions