简体   繁体   English

Java整数,以十六进制和整数

[英]Java integer to hex and to int

I have the problem, that the method does not work as expected. 我有问题,该方法无法按预期工作。 In most cases it works. 在大多数情况下,它可以工作。 However there is a case it does not work. 但是,在某些情况下它不起作用。 I have a byte array containing some values. 我有一个包含一些值的字节数组。 In hex eg: 0x04 0x42 (littleEndian). 以十六进制表示,例如:0x04 0x42(littleEndian)。 If I use the method convertTwoBytesToInt, I get a really small number. 如果我使用convertTwoBytesToInt方法,则会得到一个非常小的数字。 It should be > 16000 and not smaller than 2000. 它应该> 16000并且不小于2000。

I have two methods: 我有两种方法:

private static int convertTwoBytesToInt(byte[] a){
    String f1 = convertByteToHex(a[0]);
    String f2 = convertByteToHex(a[1]);
    return Integer.parseInt(f2+f1,RADIX16);
}

private static byte[] convertIntToTwoByte(int value){
    byte[] bytes = ByteBuffer.allocate(4).putInt(value).array();
    System.out.println("Check: "+Arrays.toString(bytes));
    byte[] result = new byte[2];
    //big to little endian:
    result[0] = bytes[3];
    result[1] = bytes[2];
    return result;
}

I call them as follows: 我称它们为:

    byte[] h = convertIntToTwoByte(16000);
    System.out.println("AtS: "+Arrays.toString(h));
    System.out.println("tBtInt: "+convertTwoBytesToInt(h));

If I use the value 16000, there is no problem, but if I use 16900, the integer value of "convertTwoBytesToInt" is 1060. 如果使用值16000,则没有问题,但是,如果使用16900,则“ convertTwoBytesToInt”的整数值为1060。

Any Idea? 任何想法?

Based on the example you provided, my guess is that convertByteToHex(byte) is converting to a single-digit hex string when the byte value is less than 0x10. 根据您提供的示例,我的猜测是,当字节值小于0x10时, convertByteToHex(byte)将转换为一位十六进制字符串。 16900 is 0x4204 and 1060 is 0x424. 16900是0x4204,而1060是0x424。

You need to ensure that the conversion is zero-padded to two digits. 您需要确保将转换零填充到两位数。

A much simpler approach is to use bit manipulation to construct the int value from the bytes: 一种更简单的方法是使用位操作从字节构造int值:

private static int convertTwoBytesToInt(byte[] a) {
    return ((a[1] & 0xff) << 8) | (a[0] & 0xff);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM