简体   繁体   中英

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?

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM