BullyWiiPlaza
BullyWiiPlaza

Reputation: 19195

Combining 4 Bytes To Integer

I have an array of bytes called contents from which I want to read bytes, shorts and integers from.

To do this, I read bytes individually and combine them by shifting.

public byte getByteValue(int fileOffset)
{
    return contents[fileOffset];
}

public short getShortValue(int fileOffset)
{
    short shortValue;

    shortValue = getByteValue(fileOffset);
    shortValue = (short) (shortValue * 256 + getByteValue(fileOffset + 1));

    return shortValue;
}

public int getIntegerValue(int fileOffset)
{
    int integerValue;

    integerValue = getShortValue(fileOffset);
    integerValue = integerValue * 256 + getByteValue(fileOffset + 2);
    integerValue = integerValue * 256 + getByteValue(fileOffset + 3);

    return integerValue;
}

When this is used on an integer value which shows up as 0x4455FF00 in a Hex Editor like HxD, the Java method however returns 0x4454FF00.

Oddly enough, getShortValue() is correct with 0x4455 and getByteValue() obviously as well.

Why does it differ? What went wrong? How do I fix it?

Upvotes: 2

Views: 185

Answers (1)

aioobe
aioobe

Reputation: 421040

Keep in mind that bytes are signed in Java (think about what happens if getByteValue(fileOffset) returns -100).

I suggest you use ByteBuffer and its getInt, getShort methods.

Your approach can be fixed by changing

public byte getByteValue(int fileOffset)
{
    return contents[fileOffset];
}

to

public int getByteValue(int fileOffset)
{
    return contents[fileOffset] & 0xFF;
}

Upvotes: 2

Related Questions