[英]convert string to uint8_t array
I have string (key_str) of size 32 bytes. 我有大小为32字节的字符串(key_str)。 I want to store each bytes in uint8_t array element key[32].
我想将每个字节存储在uint8_t数组元素键[32]中。 I tried the following:
我尝试了以下方法:
string key_str = "00001000200030004000500060007000";
uint32_t key[32] ;
uint8_t* k = reinterpret_cast <uint8_t*>(&key_str[0]);
for(int j = 0; j < 32; j++)
{
key[j]= *k;
k++;
cout<<bitset<8>(key[j])<<endl;
}
but the MSB 4 bits of the output is always 0011 because of representation of characters (0,1,...) so how can I convert it to integer? 但由于字符(0,1,...)的表示,输出的MSB 4位始终为0011,那么如何将其转换为整数?
Output sample: 00110000 .. 00110001 .. 00110010 .. 输出样本:00110000 .. 00110001 .. 00110010 ..
Your code could use some other work, but the bug, if I understand you correctly, is because you don't compensate for the offset of the ASCII character value of '0'
. 您的代码可能会使用其他一些工作,但如果我理解正确,则该错误是因为您没有补偿ASCII字符值
'0'
的偏移量 。
Try this (as close as I found it reasonable to stick to your code): 试试这个(尽可能接近我的代码):
#include <string>
#include <iostream>
#include <bitset>
using namespace std;
int main()
{
string key_str = "00001000200030004000500060007000";
uint8_t key[32] ;
for (int j = 0; j < 32; j++)
{
key[j] = static_cast<uint8_t>(key_str[j] - '0');
cout << bitset<8>(key[j]) << endl;
}
return 0;
}
Output: 输出:
00000000
00000000
00000000
00000000
00000001
00000000
00000000
00000010
...
So the key thing here in regards to your question is the subtraction of '0'
right here: key[j] = static_cast<uint8_t>(key_str[j] - '0');
所以这里关于你的问题的关键是在这里减去
'0'
: key[j] = static_cast<uint8_t>(key_str[j] - '0');
. 。
Also, if you say 另外,如果你说
I want to store each bytes in
uint8_t
array elementkey[32]
我想在
uint8_t
数组元素key[32]
存储每个字节
then perhaps it's by mistake that you defined it to be uint32_t key[32];
那么也许你错误地将它定义为
uint32_t key[32];
instead of uint8_t key[];
而不是
uint8_t key[];
. 。 I've allowed myself to correct it.
我允许自己纠正它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.