[英]Convert ASCII Byte Char array to Hex Byte Array
我想將 C++ 中的 ASCII 字節數組轉換為十六進制字節數組。 例如 ASCII 字符
Byte source[3] = {0xB1,0x8E,0x9C};
十六進制
Byte destination[6] = {0x42,0x31,0x38,0x45,0x39,0x43}
通過從 ASCII 字符映射到十六進制值
B = 42, 1 = 31, 8 = 38, E = 45, 9 = 39, C = 43
你可以用一個簡單的查找表來做到這一點:
#include <stdio.h>
typedef unsigned char Byte;
int main() {
char digits[16] = { '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
Byte source[3] = { 0xB1,0x8E,0x9C };
Byte destination[6];
for (int i = 0; i < 3; ++i) {
destination[i * 2] = digits[source[i] >> 4]; // High nibble
destination[i * 2 + 1] = digits[source[i] & 0xF]; // Low nibble
}
for (int p = 0; p < 6; ++p) printf(" 0x%02X", destination[p]);
printf("\n");
return 0;
}
編輯:您可以使代碼更簡潔,使用:
const char *digits = "0123456789ABCDEF";
但是,正如 SO 上的許多人所指出的那樣,短代碼並不總是最好的或最清晰的。 在這種情況下,編譯器可能會生成幾乎相同的機器代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.