简体   繁体   中英

Java Byte Operation - Converting 3 Byte To Integer Data

I have some byte-int operations. But I cant figure out the problem.

First of all I have a hex data and I am holding it as an integer

public static final int hexData = 0xDFC10A;

And I am converting it to byte array with this function:

public static byte[] hexToByteArray(int hexNum)
    {
        ArrayList<Byte> byteBuffer = new ArrayList<>();

        while (true)
        {
            byteBuffer.add(0, (byte) (hexNum % 256));
            hexNum = hexNum / 256;
            if (hexNum == 0) break;
        }

        byte[] data = new byte[byteBuffer.size()];
        for (int i=0;i<byteBuffer.size();i++){
            data[i] = byteBuffer.get(i).byteValue();
        }


        return data;
    }

And I want to convert 3 byte array to integer back again how can I do that? Or you can also suggest other converting functions like hex-to-3-bytes-array and 3-bytes-to-int thank you again.

UPDATE

In c# someone use below function but not working in java

 public static int byte3ToInt(byte[] byte3){
        int res = 0;
        for (int i = 0; i < 3; i++)
        {
            res += res * 0xFF + byte3[i];
            if (byte3[i] < 0x7F)
            {
                break;
            }
        }
        return res;
    }

This will give you the value:

(byte3[0] & 0xff) << 16 | (byte3[1] & 0xff) << 8 | (byte3[2] & 0xff)

This assumes, the byte array is 3 bytes long. If you need to convert also shorter arrays you can use a loop.

The conversion in the other direction (int to bytes) can be written with logical operations like this:

byte3[0] = (byte)(hexData >> 16);
byte3[1] = (byte)(hexData >> 8);
byte3[2] = (byte)(hexData);

You could use Java NIO's ByteBuffer:

byte[] bytes = ByteBuffer.allocate(4).putInt(hexNum).array();

And the other way round is possible too. Have a look at this .

As an example:

final byte[] array = new byte[] { 0x00, (byte) 0xdf, (byte) 0xc1, 0x0a };//you need 4 bytes to get an integer (padding with a 0 byte)
final int x = ByteBuffer.wrap(array).getInt();
// x contains the int 0x00dfc10a

If you want to do it similar to the C# code:

public static int byte3ToInt(final byte[] byte3) {
        int res = 0;
        for (int i = 0; i < 3; i++)
        {
        res *= 256;
        if (byte3[i] < 0)
        {
            res += 256 + byte3[i]; //signed to unsigned conversion
        } else
        {
            res += byte3[i];
        }
        }
        return res;
    }

to convert Integer to hex: integer.toHexString()

to convert hexString to Integer: Integer.parseInt("FF", 16);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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