I have a byte array obtained by automatically MYBATIS conversion. Into ORACLE DB column (RAW type) I have HEX value (example: 0x0, 0x81, 0xC801). This value is stored with maximum 2 bytes (example 1100100000000001 -> 0xC801, 0000000000000000 -> 0x0)
I have a problem when i read and convert this value.
I need to convert the byte array obtained by automatically conversion, to 16 fixed length binary string.
For example if the value in DB is 0x0:
- byte array is [0] (automatically MYBATIS conversion)
- binary string that I need must be 0000000000000000
For example if the value in DB is 0xC801:
- byte array is [0, -56, 1] (automatically MYBATIS conversion)
- binary string that I need must be 1100100000000001
How i can do that?
I tried with this solution but doesn't work with HEX value like 0x0 or 0x81 because 0x0 is mapped to "0" and 0x81 is mapped to "100000001". 0 padding is missing... and i don't know how to add the padding insite this script.
private static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();
public static String bytesToBinary(byte[] bytes) {
return hexToBin(bytesToHex(bytes));
}
public static String hexToBin(String s) {
if (StringUtils.isNotEmpty(s)) {
return new BigInteger(s, 16).toString(2);
}
return "";
}
public static String bytesToHex(byte[] bytes) {
if (bytes != null && bytes.length > 0) {
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = HEX_ARRAY[v >>> 4];
hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
}
return new String(hexChars);
}
return "";
}