我正在尝试使用 C 将十六进制字符串解码回二进制数据。我已经在 Java 中完成了这件事,并且在 C 中具有等效的编码功能,但不能完全使解码工作。看...
Java代码:
private static String encodeToHex(byte[] bytes) {
StringBuilder stringBuilder = new StringBuilder();
for (byte b : bytes) {
stringBuilder.append(String.format("%02x", b & 0xff));
}
return stringBuilder.toString();
}
private static byte[] decodeFromHex(String hexText) {
int length = hexText.length();
byte[] data = new byte[length / 2];
for (int i = 0; i < length; i += 2) {
data[i / 2] = (byte) ((Character.digit(hexText.charAt(i), 16) << 4) + Character.digit(hexText.charAt(i + 1), 16));
}
return data;
}
C代码:
void encodeToHex(const unsigned char *encryptedText, const size_t length, char *hexEncodedText) {
for (int i = 0; i < length; i++) {
if (i == 0) {
sprintf(hexEncodedText, "%02x", encryptedText[i] & 0xff);
} else {
sprintf(hexEncodedText + strlen(hexEncodedText), "%02x", encryptedText[i] & 0xff);
}
}
}
// The poor attempt. Note, I do not write C like a native
void hexDecode(char *hexEncodedText, unsigned char *decodedCipherText) {
int length = strlen(hexEncodedText);
unsigned char data[length / 2];
for (int i = 0; i < length; i += 2) {
data[i / 2] = (char) ((hexEncodedText[i] << 4) + (hexEncodedText[i + 1]));
}
memcpy(decodedCipherText, data, length / 2);
}
我想我要寻找的是 Java 的 C 等价物Character.digit(hexText.charAt(i), 16)
。有人对如何做到这一点有任何想法吗?
提前致谢。