开发者

how can i use unsigned in java

开发者 https://www.devze.com 2023-03-14 20:09 出处:网络
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 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 unsigne开发者_运维知识库d char but i don't know how. in c++ we write unsigned but how is it in java?


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)


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消