解决所有Java字节都已签名这一事实的最佳方法是什么? [英] What is the best way to work around the fact that ALL Java bytes are signed?
问题描述
在Java中,没有无符号字节。
In Java, there is no such thing as an unsigned byte.
使用某些低级代码时,有时需要使用无符号值更大的字节因为MSB被用于签名,这导致Java将它们解释为负数。
Working with some low level code, occasionally you need to work with bytes that have unsigned values greater than 128, which causes Java to interpret them as a negative number due to the MSB being used for sign.
解决这个问题的好方法是什么? (说不要使用Java不是一个选项)
What's a good way to work around this? (Saying don't use Java is not an option)
推荐答案
当从数组中读取任何单个值时,将其复制成类似的东西short或int并手动将负数转换为正值。
When reading any single value from the array copy it into something like a short or an int and manually convert the negative number into the positive value it should be.
byte[] foobar = ..;
int value = foobar[10];
if (value < 0) value += 256 // Patch up the 'falsely' negative value
写入数组时可以进行类似的转换。
You can do a similar conversion when writing into the array.
这篇关于解决所有Java字节都已签名这一事实的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!