0

I have a ASCII encoded string that looks like 3030. Each character in the ascii string needs to be converted into a 4 bit sequence and concatenated together to form a 16 bit sequence, with 4 bit padding.

For eg: 3030 should be converted into 
0011 0000 0011 0000 

(Spaces added for readability).

I'm aware that we can cast each character to a byte and and do String format operations to get the binary representation as a string. But I would want to retain the binary format because I want to do further masking on it.

Is there a way to get this byte output in java?

4

1 回答 1

0
byte chartodecimal(char x) {
    if(x >= '0' || x <= '9') { return (byte)((byte)x - (byte)'0'); }
    throw new Exception("Not a decimal digit");
}

byte[] tobcd(String s) {
    int result_len = (s.length() + 1) / 2;
    byte[] result = new byte[result_len];
    for (int i = s.length() % 2, j = 0; i < result_len; i++, j += 2) {
        result[i] = (byte)(chartodecimal(s[j]) << 4 | chartodecimal(s[j + 1]));
    }
    return result;

}

通常的警告:可能会或可能不会起作用,可能会做与您实际想要的不同的事情。

于 2013-11-10T19:09:34.840 回答