Yokz
Yokz

Reputation: 13

Splitting char into char array

I do have a char string:

uint8_t word[40] = "a9993e364706816aba3e25717850c26c9cd0d89d";  

I need to somehow split it into char array, so it would look like this:

uint32_t hfFile[5];
hfFile[0] = 0xa9993e36;  
hfFile[1] = 0x4706816a;  
hfFile[2] = 0xba3e2571;  
hfFile[3] = 0x7850c26c;  
hfFile[4] = 0x9cd0d89d;  

Later i want to check, is other array elements equal to the hfFile's elements.

My problem is, I don't know how to extract exact portions from char string, and how will it work, if

another_array[0] = 0xa9993e36;

look like this?

Upvotes: 1

Views: 474

Answers (2)

Thomas Sparber
Thomas Sparber

Reputation: 2917

You can do something like this:

int length = strlen(word);

for(int i = 0; (i*8) < length; i++)
{
    strncpy(hfFile[i], word + i*8, 8);
}

And if you want to compare those hfFile strings with another_array[0] = "0xa9993e36" you can do it like so:

if(strncmp(hfFile[0], another_array[0] + 2, 8) == 0) ...

The +2 is used to skip 0x at the beginning of another_array

Please note that this code does not contain any error checking.

Please also note that I recommend using std::string instead of C-style strings!

Upvotes: 2

gsamaras
gsamaras

Reputation: 73444

Use std::string and then, you can use string::substr to do this:

std::string word = "a9993e364706816aba3e25717850c26c9cd0d89d";
std::string hfFile[5]; // or use std::vector instead of C-array
hfFile[0] = word.substr(0, 8);
hfFile[1] = word.substr(8, 16);
hfFile[2] = word.substr(16, 24);
hfFile[3] = word.substr(24, 32);
hfFile[4] = word.substr(32, 40);

And then the comparison can be as simple as this:

if(hfFile[0] == "a9993e36")
    std::cout << "equal\n";

Following the approach won't hurt performance. Compile with optimization flags and you will be fine. I suspect you are a victim of premature optimization here.

Upvotes: 3

Related Questions