日期:2014-05-20  浏览次数:20712 次

基础的问题:byte[]转int
byte[] bt = new byte[3];
bt[0] = 0x66;
bt[1] = 0x65;
bt[2] = 0x61;
将数组bt转换成int,结果应该是4074,上网搜了很多方法,转换结果都不对,应该如何转换呢?

------解决方案--------------------
Java code
    public static void main(String args[]) {
        byte[] bt = new byte[3];
        bt[0] = 0x66;
        bt[1] = 0x65;
        bt[2] = 0x61; 
        System.out.println(Integer.parseInt(new String(bt), 16));
    }

------解决方案--------------------
public static int bytesToInt(byte[] ba) {

if (ba.length <= 0 || ba.length > 4) {
throw new RuntimeException();
}
int result = 0;
int temp = 0;
for (int i = ba.length - 1; i >= 0; i--) {
temp = ba[i] & 0xFF;
result = result * 0x100 + temp;
}
return result;
}
------解决方案--------------------
探讨
byte[] bt = new byte[3];
bt[0] = 0x66;
bt[1] = 0x65;
bt[2] = 0x61;
将数组bt转换成int,结果应该是4074,上网搜了很多方法,转换结果都不对,应该如何转换呢?

------解决方案--------------------
18楼思路比较好;
用byte构造String的方法很不好,有编码问题,位到字节不整除的时候有问题。
------解决方案--------------------
日,看了一些楼上们的回答才知道楼主到底要干什么~~~切,让我白费功夫~~~