public static int decode(byte src) {
int i; i = src;
i &= 0xFF; return i;
} public static int decode(byte[] src, ByteOrder endian) {
int result; if (src.length < 1 || src.length > 4) {
throw new IllegalArgumentException("src.length == " + src.length);
} result = 0; if (endian == ByteOrder.BIG_ENDIAN) {
for (int i = 0; i < src.length; i++) {
result |= decode(src[i]) << (i * 8);
}
} else if (endian == ByteOrder.LITTLE_ENDIAN) {
for (int i = 0, j = src.length - 1; i < src.length; i++, j--) {
result |= decode(src[i]) << (j * 8);
}
} else {
throw new NullPointerException("endian == null");
} return result;
}做个类把这两个函数放进去
int result = decode(b, ByteOrder.BIG_ENDIAN);
int i; i = src;
i &= 0xFF; return i;
} public static int decode(byte[] src, ByteOrder endian) {
int result; if (src.length < 1 || src.length > 4) {
throw new IllegalArgumentException("src.length == " + src.length);
} result = 0; if (endian == ByteOrder.BIG_ENDIAN) {
for (int i = 0; i < src.length; i++) {
result |= decode(src[i]) << (i * 8);
}
} else if (endian == ByteOrder.LITTLE_ENDIAN) {
for (int i = 0, j = src.length - 1; i < src.length; i++, j--) {
result |= decode(src[i]) << (j * 8);
}
} else {
throw new NullPointerException("endian == null");
} return result;
}做个类把这两个函数放进去
int result = decode(b, ByteOrder.BIG_ENDIAN);
class Test
{
public static void main (String[] agrs) {
byte[] b={0x10,0x10,0x10,0x10}; //big-endian
BigInteger bigNum = new BigInteger(b);
int intNum = bigNum.intValue();
System.out.println(intNum);
}
}
int c=(int)b;这只有在 b 的最高位为0的情况下,也就是 b 的值小于 128 时可行
当b>=128时,就会出来是一个负数,所以正确的应该是在 下面再加一句if(c<0){
c+=256;
}
class Test
{
public static void main (String[] agrs) { 修改了第一个数的第一位就出来负数了
byte[] b={(byte)0xA0,0x10,0x10,0x10}; //big-endian
BigInteger bigNum = new BigInteger(b);
int intNum = bigNum.intValue();
System.out.println(intNum);
}
}
public static void main(String[] args) {
byte[] b = {
(byte) 0x80, 0x00, 0x00, 0x00};
int result = decode(b, ByteOrder.BIG_ENDIAN); System.out.println(result);
} public static int decode(byte src) {
int i; i = src;
i &= 0xFF; return i;
} public static int decode(byte[] src, ByteOrder endian) {
int result; if (src.length < 1 || src.length > 4) {
throw new IllegalArgumentException("src.length == " + src.length);
} result = 0; if (endian == ByteOrder.BIG_ENDIAN) {
for (int i = 0; i < src.length; i++) {
result |= decode(src[i]) << (i * 8);
}
}
else if (endian == ByteOrder.LITTLE_ENDIAN) {
for (int i = 0, j = src.length - 1; i < src.length; i++, j--) {
result |= decode(src[i]) << (j * 8);
}
}
else {
throw new NullPointerException("endian == null");
} return result;
}}输出结果:
128好像也有点问题,应该是128*256*256*256
for(int i=0;i<b.length;i++)
{
result|=(b[i]&0xff); //此处忽略byte的符号位
result<<=8;
}
如果有符号位又如何呢?big edian是什么意思?不好意思问你这个
little edian 10100000 00000000 ==> 00000000 10100000
int result=0;
for(int i=0;i<b.length;i++)
{
result<<=8;
result|=(b[i]&0xff); //此处忽略byte的符号位
}