C++---16进制的字符串转16进制数
转:https://blog.csdn.net/Mmagic1/article/details/111413079
#include <stdio.h> #include <stdlib.h> #include <string.h> int char2bits(char ch) { int bits = 0; if (ch >= 'a' && ch <= 'z') { bits = ch - 'a' + 10; } else if (ch >= 'A' && ch <= 'Z') { bits = ch - 'A' + 10; } else if (ch >= '0' && ch <= '9') { bits = ch - '0'; } else { bits = -1; } return bits; } //#define CHARSIZE 3 几个字符转为一个16进制 #define CHARSIZE 2 int hex2bytes(const char* hex, char* bytes, int size) { int len = strlen(hex); int nbytes = (len + 1) / CHARSIZE; if (nbytes > size) { return -1; } int n = 0; for (n = 0; n != nbytes; ++n) { int lndx = n * CHARSIZE; int rndx = lndx + 1; int lbits = char2bits(hex[lndx]); int rbits = char2bits(hex[rndx]); if (lbits == -1 || rbits == -1) { return -1; } bytes[n] = (lbits << 4) | rbits; } return nbytes; } int main(int argc, char* const argv[]) {//07 0A 02 10 03 00 00 00 00 00 const char* hex = "48656c6c6f20576f726c6400";//Hello World char stream[12]; int nbytes = hex2bytes(hex, stream, sizeof(stream)); if (nbytes != -1) { int i = 0; for (; i < nbytes; ++i) { printf("%02x ", stream[i]); } printf("\n"); for (i = 0; i < nbytes; ++i) { printf("%c", stream[i]); } } return 0; }
分类:
C/C++
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· AI与.NET技术实操系列(六):基于图像分类模型对图像进行分类