0

我在Java中将无符号字节转换为int有一个奇怪的问题。十六进制值 0x81(十进制的 129)总是被错误地解释为 63。其他所有值都正常工作。也许这是因为字节在转换之前存储在字符串中。

//some string
String text=new String(bytearray);
//create an iterator to go through the bytes
byte[] bytes=text.getBytes();
List<Byte> list=new ArrayList<Byte>();
for(byte i:bytes){
list.add(i);
}
Iterator<Byte> it=list.iterator();
while(it.hasNext()){
//bitwise AND 0xFF to remove 2's complement
int a=it.next()&0xFF;
}

有没有什么办法解决这一问题?

解决方案

//some string, this time I use a char[] to fill it.
String text=new String(chararray);
//create an iterator to go through the bytes
char[] chars=text.toCharArray();
List<Byte> list=new ArrayList<Byte>();
for(char i:chars){
list.add((byte)i);
}
Iterator<Byte> it=list.iterator();
while(it.hasNext()){
//bitwise AND 0xFF to remove 2's complement
int a=it.next()&0xFF;
}
4

1 回答 1

3

字节数据类型是有8-bit符号二进制补码整数。它具有最小值-128和最大值127(包括)。

于 2013-05-14T22:14:53.770 回答