ascii转hex
int Ascii2Hex(const char* ascii, char* hex) { int i, len = strlen(ascii); char chHex[] = "0123456789ABCDEF"; for (i = 0; i<len; i++) { hex[i * 3] = chHex[((BYTE)ascii[i]) >> 4]; hex[i * 3 + 1] = chHex[((BYTE)ascii[i]) & 0xf]; hex[i * 3 + 2] = ' '; } hex[len * 3] = '\0'; return len * 3; }
hex转ascii
int Hex2Ascii(const char* hex, char* ascii, int maxCount) { int len = strlen(hex), tlen, i, cnt; for (i = 0, cnt = 0, tlen = 0; i<len && tlen < maxCount; i++) { char c = toupper(hex[i]); if ((c >= '0'&& c <= '9') || (c >= 'A'&& c <= 'F')) { BYTE t = (c >= 'A') ? c - 'A' + 10 : c - '0'; if (cnt) ascii[tlen++] += t, cnt = 0; else ascii[tlen] = t << 4, cnt = 1; } } return tlen; }
hexdump函数
void hexdump(const void* _data, uint32_t size) { const uint8_t* data = (const uint8_t*)_data; unsigned int offset = 0; while (offset < size) { printf("%08x ", offset); size_t n = size - offset; if (n > 16) { n = 16; } for (size_t i = 0; i < 16; ++i) { if (i == 8) { printf(" "); } if (offset + i < size) { printf("%02x ", data[offset + i]); } else { printf(" "); } } printf(" "); for (size_t i = 0; i < n; ++i) { if (isprint(data[offset + i])) { printf("%c", data[offset + i]); } else { printf("."); } } printf("\n"); offset += 16; } }