简体   繁体   English

使用sprintf将十六进制0xAABBCC转换为字符串“ AA:BB:CC”

[英]Convert hex 0xAABBCC to string “AA:BB:CC” using sprintf

I have a hex number 0xaabbcc which I would like convert and format into a char string as AA:BB:CC . 我有一个十六进制数字0xaabbcc ,我想将其转换并格式化为AA:BB:CC的char字符串。

using sprintf(myStr, %X, 0xaabbcc); 使用sprintf(myStr, %X, 0xaabbcc); results in char myStr[] = "AABBCC"; 结果为char myStr[] = "AABBCC";

Is it possible to use sprintf or some other function to convert and format 0xaabbcc to AA:BB:CC ? 是否可以使用sprintf或其他函数将0xaabbcc转换并格式化为AA:BB:CC

You need to surround the specifier string with quotes. 您需要用双引号将说明符字符串引起来。 The printf family receives a const char* as the format string. printf系列接收一个const char*作为格式字符串。 %x alone outside of a string means something modulo by x, and will result in compiler error if there's no integer before % like in your case %x仅在字符串外表示对x进行模运算,如果%前面没有整数(如您的情况),则会导致编译器错误

After that just split the bytes you want to print 之后,只需分割要打印的字节

unsigned v = 0xAABBCCU;
sprintf(myStr, "%02X:%02X:%02X", v >> 16, (v >> 8) & 0xFFU, v & 0xFFU); // or
sprintf(myStr, "%02X:%02X:%02X", v >> 16, (uint8_t)(v >> 8), (uint8_t)v);

However since you're using C++ it'll be safer to use std::string 但是,由于您使用的是C ++,因此使用std :: string会更安全

std::stringstream myStr;
myStr << std::hex << std::setfill('0')
      << std::setw(2) << (v >> 16)
      << std::setw(2) << ((v >> 8) & 0xFFU)
      << std::setw(2) << (v & 0xFFU)

If you want to stick with printf and you are using GCC (or maybe Clang, but I can't find anything documented) then you can use printf cusomization . 如果您想坚持使用printf并且正在使用GCC(或者也许是Clang,但我找不到任何记录的文档),则可以使用printf定制

Frankly @phuclv's answer is probably better. 坦白说,@ phuclv的答案可能更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM