lll
lll

Reputation: 19

How to cast char* to uint32_t in C?

I have an array of char* defined as char *data_ptr = "ABCDEFGHIJKLMNOPQRSTUVWX". Also, I have a write buffer declared as static uint32_t wr_buff[32].

I iteratively extract 4 bytes from the array and put them in a substring of char defined as char substr[4].

What I want to do is put those 4 bytes into the write buffer without changing their value but I firstly need to cast each element of the substring to uint32_t.

I tried the following line but it didn't work:

wr_buffer = (uint32_t)substr[0] << 24 | (uint32_t)substr[1] << 16 | (uint32_t)substr[2] << 8 | (uint32_t)substr[3];

how can I save those 4 bytes to the uint32_t buffer?

Upvotes: 0

Views: 877

Answers (1)

Ptit Xav
Ptit Xav

Reputation: 3219

You over complicated things :

char *data_ptr = "ABCDEFGHIJKLMNOPQRSTUVWX";
static uint32_t wr_buff[32];
char *posInEntry ;
char *posInOutput;

posInEntry = data_ptr;
posInOutput = (char *) wr_buff;
while (posInEntry < strlen(data_ptr)) {
    posInOutput[3] = posInEntry++;
    posInOutput[2] = posInEntry++;
    posInOutput[1] = posInEntry++;
    posInOutput[0] = posInEntry++;
    posInOutput += 4;
}

Note (thanks to @ user16217248 for pointing out few errors) :

  • uint32_t is defined in stdint.h
  • strlen is defined in string.h

Upvotes: 1

Related Questions