c - 将 uint8_t 转换为十六进制字符串(2 位数字)
问题描述
我目前正在使用以下打印uint8_t
到hex
:
for(int j = 0; j < len; j++) {
printf("%02X ", bytes[j]);
}
是否可以在没有for
-loop 的情况下执行此操作并将结果简单地分配给变量?
解决方案
这是一种简单的方法:
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
bool to_hex(char* dest, size_t dest_len, const uint8_t* values, size_t val_len) {
if(dest_len < (val_len*2+1)) /* check that dest is large enough */
return false;
*dest = '\0'; /* in case val_len==0 */
while(val_len--) {
/* sprintf directly to where dest points */
sprintf(dest, "%02X", *values);
dest += 2;
++values;
}
return true;
}
int main() {
uint8_t values[256];
char buf[sizeof(values)*2+1]; /* one extra for \0 */
for(size_t i=0; i<256; ++i)
values[i] = i;
if(to_hex(buf, sizeof(buf), values, sizeof(values)))
printf("%s\n", buf);
}
输出:
000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F202122232425262728292A2B2C2D2E2F303132333435363738393A3B3C3D3E3F404142434445464748494A4B4C4D4E4F505152535455565758595A5B5C5D5E5F606162636465666768696A6B6C6D6E6F707172737475767778797A7B7C7D7E7F808182838485868788898A8B8C8D8E8F909192939495969798999A9B9C9D9E9FA0A1A2A3A4A5A6A7A8A9AAABACADAEAFB0B1B2B3B4B5B6B7B8B9BABBBCBDBEBFC0C1C2C3C4C5C6C7C8C9CACBCCCDCECFD0D1D2D3D4D5D6D7D8D9DADBDCDDDEDFE0E1E2E3E4E5E6E7E8E9EAEBECEDEEEFF0F1F2F3F4F5F6F7F8F9FAFBFCFDFEFF
为了完整起见,这是一个使用查找表而不是自包含版本sprintf
:
bool to_hex(char* dest, size_t dest_len, const uint8_t* values, size_t val_len) {
static const char hex_table[] = "0123456789ABCDEF";
if(dest_len < (val_len*2+1)) /* check that dest is large enough */
return false;
while(val_len--) {
/* shift down the top nibble and pick a char from the hex_table */
*dest++ = hex_table[*values >> 4];
/* extract the bottom nibble and pick a char from the hex_table */
*dest++ = hex_table[*values++ & 0xF];
}
*dest = 0;
return true;
}
推荐阅读
- c# - 如何使用 Xamarin 为 Android 应用打开新窗口/页面?
- linux - 如何从 nginx 站点中的 URL 中删除端口号
- javascript - 有时 select2 在 moodle 插件中不起作用/加载
- python-3.x - 如何从隐藏的系统托盘图标访问弹出菜单
- tomcat - TomEE:忽略 docBase 被扫描
- node.js - Docker Postgres 连接被拒绝
- python - Pymongo pymongo.errors.ServerSelectionTimeoutError 使用示例代码时
- java - spring boot 微服务给出:java.net.SocketException: Connection reset
- javascript - node.js 在发送 html 页面之前对用户进行身份验证
- multithreading - @Asynchronous EJB 和休眠连接问题