0的C语言程序16进制,C十六进制解析

获取包含给定数字的十六进制表示的字符串的C -ish方法是对流使用十六进制修饰符,如本例所示:

const int i = 0xdeadbeef;

cout << "0x" << hex << i << endl; // prints "0xdeadbeef"

您可以在字符串流中使用相同的修饰符,以防需要在字符串变量中使用十六进制表示形式:

const int i = 0xdeadc0de;

ostringstream stream;

stream << "0x" << hex << i;

const string s = stream.str(); // s now contains "0xdeadc0de"

更新:

如果您的输入数据以包含字符串字符的十六进制表示形式的字符串给出,则需要知道输入字符串的编码才能正确显示.在最简单的情况下,字符串类似ASCII,将一个字节映射到一个字符.因此,在给定输入“414243”中,每两个字符(“41”,“42”,“43”)映射到ASCII值(65,66,67),其映射到字符(“A”,“B”,“C”).

C:

const string hexData = "414243";

assert( hexData.size() % 2 == 0 );

ostringstream asciiStream;

istringstream hexDataStream( hexData );

vector buf( 3 ); // two chars for the hex char,one for trailing zero

while ( hexDataStream.good() ) {

hexDataStream.get( &buf[0],buf.size() );

if ( hexDataStream.good() ) {

asciiStream << static_cast( std::strtol( &buf[0],16 ) );

}

}

const string asciiData = asciiStream.str(); // asciiData == "ABC"

使用< cstdlib>中的std :: strtol使这很容易如果您坚持为此使用模板类,请使用std :: stringstream将单个子字符串(如“41”)转换为十进制值(65).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值