Reputation: 2958
I have this code here in Java that I wish to convert to PHP. It is possibly related to converting from ascii to binary, then to hex, but I am not quite sure myself. Could anybody help please?
String clearKey = "test";
char [] hexArray = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
byte [] bytes = clearKey.getBytes();
String keyId = "";
for (int i = 0 ; i < clearKey.length() ; i ++) {
keyId = keyId + hexArray[(bytes[i] & 0xFF) / 16] + hexArray[(bytes[i] & 0xFF) % 16];
}
System.out.println(keyId);
Here is what I got so far:
The second line of the code can probably be converted into this:
$bytes = bin2hex($clearKey);
But I don't know what the equivalent of following code in php:
hexArray[(bytes[i] & 0xFF) / 16] + hexArray[(bytes[i] & 0xFF) % 16];
Additional Information
I converted this code into correct Java syntax.
Upvotes: 0
Views: 263
Reputation: 54694
It's a hex encoder using table lookup. It converts a string to bytes using the default character encoding of the platform. Then it converts those bytes to hexadecimals. The line you question calculates the hex digit for the high and low 4 bits of the byte. The entire line therefore encodes a single byte to two hexadecimal characters.
The PHP equivalent of this Java code is
$keyId = unpack('H*', $clearKey)[1];
Upvotes: 1