0

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.

4
  • 1
    This is not Ruby code, it looks rather like Java. Commented Jan 22, 2014 at 8:01
  • @p11y Up to the point of the missing parentheses in the for/next loop, but I'm pretty sure it is Java otherwise Commented Jan 22, 2014 at 8:17
  • @owlstead yes, there are some mistakes in the code. For example, there's also no type called bytes, the author probably meant byte. However, the array notation and the getBytes() immediately made me think of Java. Commented Jan 22, 2014 at 8:22
  • I wonder if there is a way for me to run this code somewhere (after some fixes in parentheses) to help me comparing the results? Commented Jan 23, 2014 at 3:18

1 Answer 1

1

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];
Sign up to request clarification or add additional context in comments.

2 Comments

Tried this, but result is different, is there anyway you could provide a proof that the code shows similarly with the java one in my question?
Nevermind my comment above, I created here: Java: ideone.com/MZ4TLH Php: ideone.com/VDYWRs

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.