How to pour uint8_t array from 4 to uint32_t in c

I am trying to pass a uint8_t array to a uint32_t array, but it does not seem to work.
Can anyone help me on this. I need to get the uint8_t values ​​for uint32_t.
I can do it with a shift, but I think there is an easy way.

uint32_t *v4full;
v4full=( uint32_t *)v4;
while (*v4full) {
    if (*v4full & 1)
        printf("1");
    else
        printf("0");

    *v4full >>= 1;
}
printf("\n");
+5
source share
6 answers

Given the need to get the uint8_t values ​​in uint32_t and the in4_pton () specification ...

Try this with a possible byte order correction:

uint32_t i32 = v4[0] | (v4[1] << 8) | (v4[2] << 16) | (v4[3] << 24);
+10
source

If v4full is a pointer, then the line

uint32_t *v4full;
v4full=( uint32_t)&v4;

Should give an error or at least a warning to the compiler. Maybe you want to do

uint32_t *v4full;
v4full=( uint32_t *) v4;

, v4 uint8. , ...

, , , , .

, , , , , . : , ?

#include <stdio.h>
#include <inttypes.h>

int main(void) {
    uint8_t v4[4] = {1,2,3,4};
    uint32_t *allOfIt;
    allOfIt = (uint32_t*)v4;
    printf("the number is %08x\n", *allOfIt);
}

:

the number is 04030201

. - 04030201 01020304, /. , ( x86) . , , ( , [0] ), @bvj - 32- .

, , ( CPU).

+4

- , ( ).

, ,

, , , :

type1 *vec1=...;
type2 *vec2=(type2*)vec1;
// do stuff with *vec2

, , type2 - char ( unsigned char const char ..), type2 - (uint32_t ), , -O2 -O3.

" " , - , , .

, . , , :

uint32_t v4full=*((uint32_t*)v4);

-O3 -Wall ( gcc) :

warning: dereferencing type-punned pointer will break strict-aliasing rules [-Wstrict-aliasing]

, .

: , , v4 v4_full. , - " ".

+4

:

/* convert character array to integer */
uint32_t buffChar_To_Int(char *array, size_t n){
    int number = 0;
    int mult = 1;

    n = (int)n < 0 ? -n : n;       /* quick absolute value check  */

    /* for each character in array */
    while (n--){
        /* if not digit or '-', check if number > 0, break or continue */
        if((array[n] < '0' || array[n] > '9') && array[n] != '-'){
            if(number)
               break;
            else
               continue;
        }

        if(array[n] == '-'){      /* if '-' if number, negate, break */
            if(number){
               number = -number;
               break;
            }
        }
        else{      /* convert digit to numeric value   */
            number += (array[n] - '0') * mult;
            mult *= 10;
        }
    }
    return number;
}
0

, , , , uint32_t , uint8_t . , SIGBUS. uint8_t[] uint32_t[] - memcpy() . ( , , - .)

, #include <stdalign.h> alignas(uint32_t) uint8_t bytes[]. , 32- union type-pun . , malloc(), .

0

:

u32 ip;

if (!in4_pton(str, -1, (u8 *)&ip, -1, NULL))
      return -EINVAL;

... use ip as it defined above - (as variable of type u32)

in4_pton (ip) - .

-1

All Articles