有没有更好的方法将字节数组转换为int?

时间:2011-06-01 18:04:24

标签: java

字节数组的前3个字节只是整数,有没有更好的方法来转换它们?到目前为止,我有这个,但这只是一种糟糕的做法。

public int parse_code(byte[] bs) {
    char[] array = new char[3];
    for(int i = 0; i < 3; i++) {
        array[i] = (char) bs[i];
    }

    // Dirty way of doing it
    return Integer.parseInt(new String(array));
}

4 个答案:

答案 0 :(得分:3)

如果您知道在字节数组的开头总会有3个十进制数字,您可以直接将它们转换为整数:

public int parse_code( byte[] bs )
{
    int intval = 0;
    for( int i = 0; i < 3; i++ )
        intval = intval * 10 + ( bs[ i ] - '0' );
    return intval;
}

答案 1 :(得分:2)

您的示例代码似乎将byte与其ASCII值相关联。正确的方法是使用带有String数组和字符集的byte构造函数:

// note: throws charset exception that will never be thrown on a valid JVM
//  as all JVMs must support US-ASCII
Integer.parseInt(new String(byteArray, "US-ASCII"));

注意:如果byte不是表示整数的ASCII字符值(例如,它只是int编码为四个byte s,那么你想看看ByteBuffer课程。它具有可以从ByteBuffer转换为其他缓冲区(例如IntBuffer)的帮助程序,以启用简单的允许循环(如果它是所有类型)(而不是混合消息,例如传入的C结构)或者其他的东西)。它还具有更改的启用字节顺序的优势。

int bytesValue = ByteBuffer.wrap(byteArray).getInt();

正如x4u所指出的那样,值得注意的是ByteBuffer确实需要为每个值获得适当数量的byte s。因此,如果有[0,3],上面的getInt()方法将使用接下来的4 byte并失败(有例外)。

答案 2 :(得分:1)

如果要将其转换为int,则数组的大小应为max 4,int不应超过214783647.然后:

int i = (bs[3] << 24) + (bs[2] << 16) + (bs[1] << 8) + bs[0] ;

您必须知道的其他事项:字节数组中哪个位置适合int(big-endian vs little-endian): (而不是前面的表达式)也许你需要:
int i = (bs[0] << 24) + (bs[1] << 16) + (bs[2] << 8) + bs[3] ;

如果不是全部4个字节,则必须检查长度。

答案 3 :(得分:0)

看起来您正在尝试将123的三个字节的ASCII [49, 50, 51]转换为123。

public static long parse_code(byte... bs) {
    long value = 0;
    for(byte b: bs)
       value = value * 10 + b - '0';
    return value;
}

如果你知道它总是3个字节。

public static int parse_code(byte... bs) {
    return bs[0]*100 + bs[1]*10 + bs[2] - '0' * 111;
}
相关问题