Java不提供无符号整数类型?谢谢

来源:百度知道 编辑:UC知道 时间:2024/06/16 05:03:12

java中以无符号的形式存储和读取数据的,不提供无符号整形。
如果有人从网络上给你发送了一堆包含无符号数值的字节(或者从文件中读取的字节),那么你需要进行一些额外的处理才能把他们转换到 Java 中的更大的数值类型。
还有一个就是字节序问题。但是现在我们先不管它,就当它是“网络字节序”,也就是“高位优先”,这也是 Java 中的标准字节序。
从网络字节序中读取
假设我们开始处理一个字节数组,我们希望从中读取一个无符号的字节,一个无符号短整型和一个无符号整数。
short anUnsignedByte = 0;
char anUnsignedShort = 0;
long anUnsignedInt = 0;
int firstByte = 0;
int secondByte = 0;
int thirdByte = 0;
int fourthByte = 0;
byte buf[] = getMeSomeData();
// Check to make sure we have enough bytes
if(buf.length < (1 + 2 + 4)) doSomeErrorHandling();
int index = 0;
firstByte = (0x000000FF & ((int)buf[index]));
index++;
anUnsignedByte = (short)firstByte;

firstByte = (0x000000FF & ((int)buf[index]));
secondByte = (0x000000FF & ((int)buf[index+1]));
index = index+2;
anUnsignedShort = (char) (firstByte << 8 | secondByte);

firstByte = (0x000000FF & ((int)buf[index]));
secondB