Converting Signed byte array content to decimal with shifting in java -
i had byte array hex decimal values , converted array decimal values, using following code
byte[] content = message.getfieldvalue( "_decoder message" ).data(); int[] deccontent = new int[ content.length ]; int = 0; ( byte b : content ) deccontent[ i++ ] = b & 0xff;
now array looks deccontent = [01 00 05 00 00 00] ;
the first 2 indexes of array converted , saved int value below
int traceidlow = deccontent[ 0 ] & 0xff; int traceidhigh = deccontent[ 1 ] & 0xff; int traceid = traceidlow | ( traceidhigh << 8 );
the last 4 indexes needs converted int confused shifting whether should 8 or 16 .
how can convert last 4 indexes int value according above example value becomes
00 00 00 05 = 5 in decimal.
any ideas?
thanks
something this:
int val = deccontent[ 2 ] | (deccontent[ 3 ] << 8) | (deccontent[ 4 ] << 16) | (deccontent[ 5 ] << 24);
note integer signed in java. if value unsigned , can larger integer.max_value
have put long
instead.
a little test:
public static void main(string[] args) throws ioexception { int[] deccontent = new int[] {1,0,5,0,0,0}; int val = deccontent[ 2 ] | (deccontent[ 3 ] << 8) | (deccontent[ 4 ] << 16) | (deccontent[ 5 ] << 24); system.out.println(val); }
prints answer 5.
Comments
Post a Comment