variable-length word builder

Could someone please help me find out why this doesn't work. It supposed to build multi-byte values with variable byte lengths. Positive values below 64 bits work, but not negative values.

int byteSize = whatever;

int bitSize = whatever;

byte[] buffer =newbyte[byteSize];

soure.readFully(buffer);//I know I'm getting all the data, 'cause it would

//throw an EOFException

// reverses buffer if not right endianness (needs to be Big)

long word = 0;

for (int x = 0; x< byteSize; ++x)

word += (buffer[x] & 0xFF) << ((byteSize - 1 - x) * 8);

return word;

I know the source works, and the changing of endianness works, but the reconstructor doesn't work with negative or >56bit words.

I don't know exactly how the Java system of handling signed values works, I just deduced this code from something else I saw.

[1297 byte] By [robbix.the.bobbixa] at [2007-10-1 18:46:19]
# 1

Without knowing your input binary format, it's hard to say, but for the bit pattern of -1L use Long.toString(-1L, 2), and you'll see that it requires leading 1s all the way up to bit 64, rather than just the number of octets you're setting. I'd probably make the buffer 8, and use Arrays.fill() to set the values that are not read in to either 0xff or 0x0 depending on the high bit of the appropriate input data octet, unless it was a very performance critical section. Alternatively, a second loop that does the same w/o the array access.

Also (buffer[x] & 0xFF) will be an int, so shifting it will not work above 32 bits; force it to a long before you shift. Use 0xFFL, or a cast.

Pete

pm_kirkhama at 2007-7-11 13:53:43 > top of Java-index,Other Topics,Algorithms...
# 2
Thanks for the help.And if it clears up my question : The format is always Big-Endian, incoming bytes are rearanged if they are not in Big-endian order.
robbix.the.bobbixa at 2007-7-11 13:53:43 > top of Java-index,Other Topics,Algorithms...