0

I had a byte array with hex decimal values and I converted that array to decimal values, using the following code

byte[] content = message.getFieldValue( "_Decoder Message" ).data();
int[] decContent = new int[ content.length ];
int i = 0;
for ( byte b : content )
   decContent[ i++ ] = b & 0xff;

now the array looks like decContent = [01 00 05 00 00 00] ;

The first 2 indexes of this array is converted and saved as int value as below

 int traceIdlow = decContent[ 0 ] & 0xFF;
 int traceIdhigh = decContent[ 1 ] & 0xFF;
 int TraceId = traceIdlow | ( traceIdhigh << 8 );

The last 4 indexes needs to be converted to int as well but I am confused about the shifting whether it should be 8 or 16 .

How can I convert the last 4 indexes to int value so that according to the above example the value becomes

00 00 00 05 = 5 in decimal.

Any ideas?

Thanks

1
  • Minor (but important) point: You're not converting to "decimal", you're converting numeric values from byte to integer size. Then you're you're splitting some of those values that are in bit-packed form into individual integers. "Decimal" never enters into it. Commented Aug 28, 2013 at 15:05

2 Answers 2

1

Something like this:

int val = decContent[ 2 ] | (decContent[ 3 ] << 8)
  | (decContent[ 4 ] << 16) | (decContent[ 5 ] << 24);

Note that an integer is always signed in Java. If the value is unsigned and can get larger than Integer.MAX_VALUE you have to put it into a 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 the answer 5.

Sign up to request clarification or add additional context in comments.

1 Comment

I was expecting 5 and it sis giving a huge number
1

Are you asking how to change the order of the 4 bytes from: b0 b1 b2 b3 to: b3b2b1b0 in an int variable?

  byte[] b = {0x5, 0x44, (byte)0x7f, 0x1};      // convert to 017f4405
  int val = b[3]<<24 |  b[2]<<16 | b[1]<<8 | b[0];
  System.out.println("val="+Integer.toHexString(val)); // val=17f4405

3 Comments

and also convert it to unsigned dec
Need to add AND of 0xFF to strip sign when byte expanded to int.
@UmairIqbal - See my note above. You may PRESENT the data as decimal, but you're not converting it into decimal unless you create a character representation of it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.