Serving the Quantitative Finance Community

 
User avatar
farmer
Topic Author
Posts: 61
Joined: December 16th, 2002, 7:09 am

extracting signed and unsigned numbers from byte arrays in java

September 1st, 2011, 5:32 pm

Is this right to extract a signed short in a byte array as an unsigned int? And then insert it back in signed? public static int ByteArrayExtractSignedShortUnsigned(byte[] b, int offset) { int value = 0; value = value + b[offset+1]; value = value ^ 128; value = value * 256; value = value + b[offset]; return value; } public static void UnsignedShortEmbedSignedToByteArray(byte[] b, int offset, int theshort) { int remain = theshort % 256; b[offset] = (byte) remain; theshort = theshort - remain; theshort = theshort / 256; theshort = theshort ^ 128; b[offset+1] = (byte) theshort; }
 
User avatar
dd3
Posts: 4
Joined: June 8th, 2010, 9:02 am

extracting signed and unsigned numbers from byte arrays in java

September 1st, 2011, 7:01 pm

Why are you using ints to read the value? You might lose the sign. short value = b[x + 1] << 8 | b[x];You only have to promote the data type when you want to read unsigned values.If you're getting strange values maybe your endianness is wrong.
Last edited by dd3 on August 31st, 2011, 10:00 pm, edited 1 time in total.
 
User avatar
farmer
Topic Author
Posts: 61
Joined: December 16th, 2002, 7:09 am

extracting signed and unsigned numbers from byte arrays in java

September 2nd, 2011, 2:23 pm

QuoteOriginally posted by: outrunwhat do you want to happen with negative signed shorts that are in the byte array?This is supposed to shift all numbers up by 32768 to make everything >= 0:value = value + b[offset+1];value = value ^ 128;
 
User avatar
zeta
Posts: 26
Joined: September 27th, 2005, 3:25 pm
Location: Houston, TX
Contact:

extracting signed and unsigned numbers from byte arrays in java

September 2nd, 2011, 6:47 pm

save yourself the hassle of manipulating bits for lack of an unsigned type (therein lies much anguish for C developers) and use bytebuffer