15,170,096 members
See more:
hi All,

I got a piece of code from google where i want to convert a byte array(randomly generated) to hex string. i dint understand few code of lines..can any one help please.??

The three functions i used :

Java
```public static String CellKeysGeneration() {

byte[] btba = new byte[5];

Random r = new Random();

r.nextBytes(btba);

for (int i = 0; i < btba.length; i++) {

btba[i] = btba[i];

}
String str = tohexString(btba);
return str;
}

public static String tohexString(byte[] bytes) {

StringBuffer sb = new StringBuffer(bytes.length * 2);

for (int i = 0; i < bytes.length; i++) {
sb.append(tohex(bytes[i] >> 4));
sb.append(tohex(bytes[i]));

}

return sb.toString();

}

public static char tohex(int nibble) {

final char[] hexdigit = { '0', '1', '2', '3', '4', '5', '6', '7', '8',
'9', 'A', 'B', 'C', 'D', 'E' , 'F' };

return hexdigit[nibble & 0xF];
}```

1) I din't understand why always "and" operation is done only with 0xF.
2) In tohexString(), why ">>" operation with 4 is done?

Can any one help me to understand tohexString() and toHex() methods :)
Posted
Updated 17-Jan-13 3:53am
v2

## Solution 1

1. Because the value passed to the `tohex()` method is always a 4-bit value.
2. To extract the leftmost 4 bits of the byte and pass it to the `tohex()` method.

If you step through the code it goes something like:

• Select the next byte in sequence
• Right shift 4 bits and pass the resulting 4 bits (the left half) to the `tohex()` method
• Append the resulting character to the string
• Pass this byte to the `tohex()` method which masks off the right half
• Append the resulting character to the string

So the hex value `0xE7` gets shifted right passed as `0x0E` which is masked with `0x0F` giving `0x0E`. Next the value `0xE7` gets passed, which is masked with `0x0F` giving `0x07`.
Espen Harlinn 17-Jan-13 16:52pm

Richard MacCutchan 18-Jan-13 4:53am

Thanks.

## Solution 2

Quote:
1) I din't understand why always "and" operation is done only with 0xF.
Such operation masks out (discards) the `4` most significant bits of the byte, because `0xF` is `00001111` in binary representation. (e.g. `10101001 & 00001111 = 00001001`).

Quote:
2) In tohexString(), why ">>" operation with 4 is done?
This 'moves the right nibble to the left', that is the `4` most significant bits of the byte replace the `4` least significant ones (the right shift operator `>>` moves bits to the right). Hence, for instance, `0xAB` becomes `0x0A`.
Espen Harlinn 17-Jan-13 16:52pm