Aditya Parsai Aditya Parsai - 1 year ago 167
Java Question

Converting integer to byte hex in java

I am trying to developing a java card application. There will a dynamic input string which will contain a phone number in a byte array like:

byte[] number =new byte[] {1,2,3,4,5,6,7,8,9,5};

I want this array to be changed into following array:

byte[] changed num = {(byte)0x0C, (byte)0x91, (byte)0x19, (byte)0x21, (byte)0x43, (byte)0x65, (byte)0x87, (byte)0x59}

Where first three bytes will be same always and remaining 5 will be update from the incoming array.

I have tried the following:

public static void main(String args[]){
byte[] number =new byte[] {1,2,3,4,5,6,7,8,9,5};

byte[] changednum = new byte[8];

changednum[0] = (byte)0x0C;
changednum[1] = (byte)0x91;
changednum[2] = (byte)0x19;
changednum[3] = (byte)0x(number[0] + number[1]*10);
changednum[4] = (byte)0x(number[2] + number[3]*10);
changednum[5] = (byte)0x(number[4] + number[5]*10);
changednum[6] = (byte)0x(number[6] + number[7]*10);
changednum[7] = (byte)0x(number[8] + number[9]*10);



But the last 5 values are not being converted to byte value


Answer Source

This line

changednum[3] = (byte)0x(number[0] + number[1]*10);

could be done with a complicate set of String manipulation how simple maths will do what you want.

changednum[3] = (byte)(number[0] + number[1]*16);

The *16 is needed because you appear to be assuming the number is in hexadecimal.

You could use a loop

for (int i = 0; i < 4; i++)
    changednum[i+3] = (byte)(number[i*2] + number[i*2+1]*16);

or using += to avoid the cast

for (int i = 0; i < 4; i++)
    changednum[i+3] += number[i*2] + number[i*2+1]*16;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download