将二进制字符串转换为十六进制字符串C [英] Convert binary string to hexadecimal string C

查看:527
本文介绍了将二进制字符串转换为十六进制字符串C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如标题所述,我对将二进制字符串转换为C中的十六进制字符串的最佳方法感兴趣.二进制字符串最多为4位,因此最好转换为单个十六进制char.

As the title said I was interested in the best way to convert a binary string to a hexadecimal string in C. The binary string is 4 bits at most so converting into a single hexadecimal char would be best.

感谢您的帮助,我不确定是否有内置功能可以简化此操作,所以请不要自己尝试发布.

Thanks for any help, I'm not sure if there's something built in to make this easier so don't have my own attempt to post yet.

推荐答案

您可以使用strtol将二进制字符串转换为整数,然后使用sprintf将整数转换为十六进制字符串:

You can use strtol to convert the binary string to an integer, and then sprintf to convert the integer to a hex string:

char* binaryString = "1101";

// convert binary string to integer
int value = (int)strtol(binaryString, NULL, 2);

// convert integer to hex string
char hexString[12]; // long enough for any 32-bit value, 4-byte aligned
sprintf(hexString, "%x", value);

// output hex string
printf(hexString);

输出:

d

如果保证它是一个十六进制字符,请使用hexString[0].

If it's guaranteed to be a single hexadecimal character just take hexString[0].

这篇关于将二进制字符串转换为十六进制字符串C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆