将字符串转换为字节(unsigned char)数组cpp [英] converting a string to byte (unsigned char) array cpp

查看:216
本文介绍了将字符串转换为字节(unsigned char)数组cpp的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个简单的问题有真正的麻烦。
我有一个这样的字符串:

having real trouble with this simple issue. I have a string like this:

std::string msg = "00 00 00 00 00 06 01 05 00 FF 00 00";

我想要:

unsigned char bbuffer[12] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x01, 0x05, 0x00, 0xFF, 0x00, 0x00 };

有什么办法呢?

推荐答案

如果可能,我建议使用 std :: vector< unsigned char>

If at all possible, I'd advise using a std::vector<unsigned char> instead of an actual array.

使用它,我想我会做这样的:

Using that, I guess I'd do something like this:

std::istringstream buffer(msg);

std::vector<unsigned char> bbuffer;

unsigned int ch;
while (buffer >> std::hex >> ch)
    bbuffer.push_back(ch);

如果你真的坚持数组,你可以这样做:

If you really insist on the array, you could do something like:

std::istringstream buffer(msg);

char bbuffer[12];

unsigned int ch;
for (int i=0; buffer >> std::hex >> ch; i++)
    bbuffer[i] = ch & 0xff;

但通常优先使用向量。

这篇关于将字符串转换为字节(unsigned char)数组cpp的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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