Question

I'm trying to flip some bytes around in Java and the function I have is working correctly for some bytes and failing for others.

The function I am using is this:

public static int foldInByte(int m, int pos, byte b) {
    int tempInt = (b << (pos * 8));
    tempInt = tempInt & (0x000000ff << (pos * 8));
    m = m | tempInt;
    return m;
}

And the code that implements this is:

byte[] bitMaskArray = new byte[]{
                            byteBuffer.get(inputIndex),
                            byteBuffer.get(inputIndex + 1),
                            byteBuffer.get(inputIndex + 2),
                            byteBuffer.get(inputIndex + 3)};
                        int tempInt = 0;

                        tempInt = foldInByte(0, 3, bitMaskArray[3]);
                        tempInt = foldInByte(tempInt, 2, bitMaskArray[2]);
                        tempInt = foldInByte(tempInt, 1, bitMaskArray[1]);
                        tempInt = foldInByte(tempInt, 0, bitMaskArray[0]);

                        bitMask = tempInt;

The bytes are being read from a ByteBuffer with the byteOrder being Little Endian.

For example, the bytes 00 01 B6 02 set the bitMask to: 2B60100 - which works perfectly in my program.

However, if the bytes are A0 01 30 00, the bitMask is set to: 3001A0 - which has stipped the last zero from the bitmask.

Is there any way I can stop Java from stipping off trailing zeros?

I hope that makes sense.

Thanks

Tony

Was it helpful?

Solution

The zeros are not being stripped -- both examples cited are correct.

  • 00 01 B6 02 is the 4-byte little-endian for 2B60100
  • A0 01 30 00 is the 4-byte little-endian for 3001A0

The zeros are there, but probably just not being printed. The System.out.print family of calls will not print leading zero digits.

I might mention that your method is needlessly complex. Here is a single method that computes the same value:

static int extractLittleEndian4(byte[] buf, int index)
{
    int a = buf[index+0]&0xff, b = buf[index+1]&0xff, c = buf[index+2]&0xff, d = buf[index+3]&0xff;
    return a | (b << 8) | (c << 16) | (d << 24);
}

OTHER TIPS

It looks like you have a ByteBuffer filled with your bytes already. Why don't you let the ByteBuffer reverse the bytes for you? Just add the bytes to the buffer (BIG_ENDIAN is the default if you want to add an integer instead of bytes) and then change the order before reading the integer.

byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
int output = byteBuffer.getInt(0);

If all you're doing is reversing the byte order, let the library do the work for you. If you happened to start with an integer value, you can even just do this:

int input = ...;
int output = Integer.reverseBytes(input);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top