c ++字符串到uint8_t

时间:2012-10-15 10:52:20

标签: c++ string casting

我已下载了一张图片,并将其保存在std::string中。 现在我想在以下条件下使用/打开它:

typedef uint8_t byte //1 byte unsigned integer type.  
static open(const byte * data, long size)

如何从string投射到byte*

/编辑:
我已经尝试过了:

_data = std::vector<byte>(s.begin(), s.end()); 
//_data = std::vector<uint8_t>(s.begin(), s.end());  //also fails, same error
_p = &_data[0];
open(_p, _data.size())

但我明白了:
未定义引用'open(unsigned char const *,long)'
为什么它错误地将字节解释为char?!

/ EDIT2: 只是为了测试它我改为函数调用

 open(*_p, _data.size())

然后我得到:

error: no matching function for call to 'open(unsigned char&, size_t)'
[...] open(const byte*, long int) <near match>

因此确定了这个功能......

2 个答案:

答案 0 :(得分:2)

两种可能性:

1)常见的一个。在您的系统上,char是2的补码或者是无符号的,因此将chars作为无符号字符读取是“安全的”,并且(如果char已签名)结果与转换相同已签名为无签名。

在这种情况下,请使用reinterpret_cast<const uint8_t*>(string.data())

2)不常见的一个。在您的系统上,char已签名,而不是2的补码,因此char *ptr指向负值时,*(uint8_t*)ptr的结果不等于(uint8_t)(*ptr)。然后根据open实际对数据执行的操作,上面可能没问题,或者您可能需要将数据从字符串复制到uint8_t的容器中,然后进行转换。例如,vector<uint8_t> v(string.begin(), string.end());。然后使用&v[0] ,前提是长度不是0 (与字符串不同,即使您从未取消引用它,也不允许指向空向量的数据)。< / p>

非二进制补充系统几乎不存在,即使有一个,我认为char签署而不是2补码的系统提供uint8_t的可能性相当小。 all(因为如果它确实那么它还必须提供int8_t)。所以(2)只服务于迂腐的完整性。

  

为什么它错误地将字节解释为char

没错,uint8_t是您系统上unsigned char的typedef。

答案 1 :(得分:0)

std::string string_with_image;

string_with_image.data();