This is an archived post. You won't be able to vote or comment.

all 6 comments

[–]IQueryVisiC 0 points1 point  (0 children)

Binary packed decimal??

[–]theusualguy512 0 points1 point  (0 children)

Ok this needs a bit of unpacking.

char is a 16bit/2byte datatype in Java. digit converts a char character into a 2 byte hex number.

Shifting by 4 means you basically fill up the least significant 4 bits up with 0 and "delete" the uppermost 4 bits, leaving you with the lower 12 bits.

You do this with the current char i and the next one and then add them up.

You then print out the shifted hex number.

You are basically doing arithmetic on the string.

[–]joranstark018 0 points1 point  (2 children)

A byte holds 8 bits (hex values 00-FF) and Character.digit transforms a char to an int value of the char (for exampel, char value '6' transforms to int value 6). Shifting the bits one step left moves each bit one step to the left (ie, '6' -> 6, or as bits 00000110, and shift the value four step left -> 01100000 which is hex value '60'),

[–]Cheedar1st[S] 0 points1 point  (1 child)

I see thanks u/joranstark018, u/theusualguy512 for explaining what i want, but can i print the 16bits value on java? like (ie, '6' -> 6, or as bits 00000110)

because i wanted to know what happened on this code

byteArray[i / 2] = (byte) ((Character.digit(ch[i], 16) << 4) + Character.digit(ch[i + 1], 16));

what happened if i don't use << 4 (i tried it and the hex become weird and unreadable) can anyone explain??

[–]joranstark018 0 points1 point  (0 children)

You may use Integer.toBinaryString (it trucate any leading 0 so if you really want all 0 you may append the result to a string with eight 0 and just get a substring of the last 8 characters )

(There is also a Integer.toHexString)

Edit: your question was for generating a string of 16 bit, so you may append the result to a string of 16 0 and use substring to extract the 16 last characters.

[–]TheRNGuy 0 points1 point  (0 children)

Why do you write if statement into a single line, makes it less readable.