Shaan_B
Shaan_B

Reputation: 1838

Explanation of android code

i found a code that converts a hex string to binary. This is the code `

public static byte[] hexStringToBytes(String hexString) {
        if (hexString == null || hexString.equals("")) {
            return null;
        }
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return d;
    }

public static byte charToByte(char c) {
    System.out.println((byte) "0123456789ABCDEF".indexOf(c));
    return (byte) "0123456789ABCDEF".indexOf(c);
}

The code works perfectly but i am not able to understand the following line of code ie how it is working d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));. Can anyone explain what this code is doing. It is going very difficult to work on binary code. Also can anyone provide a link for some documentation that explains with some example how to work with binary codeing.

Upvotes: 0

Views: 90

Answers (2)

pkalinow
pkalinow

Reputation: 1741

Gebe Sechan's answer is perfectly correct. I would add that explanation of bitwise and bit shift operators could be found with ease if you know how they are called. For example, here is the official tutorial

Upvotes: 0

Gabe Sechan
Gabe Sechan

Reputation: 93728

<< means to shift the value to the left by 4 bits. So if the value is 0000001, shifting it left by 4 gives you 00010000. | means ORing 2 values bit by bit.

charToByte is going to take a single character in the range 0...9, A...F and return its hex value- which will happen to be 0 to 15 (which fits in 4 bits).

If you have 2 values that we know are 4 bits big, shifting one left by 4 bits and ORing them together will combine them into 1 byte- the first value will be in the 4 biggest bits of the byte, the other value will be in the 4 smallest bits of the byte.

Upvotes: 2

Related Questions