Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!

# byte to hex

duhit Choudhary
Ranch Hand
Posts: 64

now the problem in my code is only that compiler is not taking the same value as given in the array. I wanted to take values like 58, 80, D, 1, 4 and checksum of the same. so now please help me and tell me how can I obtain the above values from the values given in my code in the array.
i.e how can i make my byte array to be appear like this for the compile so it can give the correct output

Jim Pouwels
Ranch Hand
Posts: 61
When you print a value of the array, f.e. like this:

The value will be printed as a decimal. The value 0x58 in hex equals 88 in dec.

You can use:

duhit Choudhary
Ranch Hand
Posts: 64
i got your point... so how can i make values comes exactly as they are appearing without including "0x"???

Jim Pouwels
Ranch Hand
Posts: 61

duhit Choudhary
Ranch Hand
Posts: 64
Jim Pouwels wrote:When you print a value of the array, f.e. like this:

The value will be printed as a decimal. The value 0x58 in hex equals 88 in dec.

You can use:

i have done the same thing but still i am getting problem.. here is my code...

Jim Pouwels
Ranch Hand
Posts: 61
for(int i = 0; i < size ; i++)
{
String str = scanner.next();
int x = Integer.parseInt(str,16);
String hexString = Integer.toHexString(x);
int y = Integer.parseInt(hexString,16);
byteArray[i] = (byte)y;
}

Your code looks a bit weird. You're mixing up values and representations of the values.

At this point you've got your correct int value. F.e. you typed 17 (of which you say it's a hex number). This int value now contains the value 23. Which is correct.

You can now store this value in your bytearray. And when you want to print it, you can use my code in order to represent it in a hex format.

Campbell Ritchie
Sheriff
Posts: 48967
60
Goi through the Java Tutorials an use ctrl-F-“formatting”, and you get four hits: look at 1 and 3. You can format a byte in two hex digits with the %02x tag, and, if you wish, prefix that with 0x.

Winston Gutkowski
Bartender
Posts: 10417
63
duhit Choudhary wrote:i.e how can i make my byte array to be appear like this for the compile so it can give the correct output...

Well, what you wrote as output is likely to be very confusing. If someone sees the string
"(byte) 58"
without any indication of what they're looking at, the chances are that they will assume (incorrectly) that it's a decimal number. That's why Java uses the '0x' notation.

Winston

Eduardo Avelar
Greenhorn
Posts: 1
Calculate checksum for a byte array

for (i=0;i<data.length;i++){
checksum += 0xff & data[i];
}

Campbell Ritchie
Sheriff
Posts: 48967
60
Welcome to the Ranch

Did you have a questions about checksums? Where did you find that algorithm?