3

I have string (key_str) of size 32 bytes. I want to store each bytes in uint8_t array element key[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?

Output sample: 00110000 .. 00110001 .. 00110010 ..

1
  • Do you have a guarantee that the string always will have at least 32 bytes of input (in given example, sure you have, but in your real code?)? If not, absolutely add a length check or iterate only up to std::min(key_str.length(), 32). Instead of literal 32, prefer using sizeof(key)/sizeof(*key), you can then change array size without danger of forgetting to adjust the other places. If you use std::array instead of raw array, you can use its size() member instead of the ugly, but otherwise necessary division by size of first element (be aware of sizeof always giving size in bytes!) Commented Aug 28, 2018 at 8:32

1 Answer 1

3

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'.

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');.

Also, if you say

I want to store each bytes in uint8_t array element key[32]

then perhaps it's by mistake that you defined it to be uint32_t key[32]; instead of uint8_t key[];. I've allowed myself to correct it.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.