10

I am trying to cast an array of uint8_t to an array of uint32_t, but it seems not to be working.
Can any one help me on this. I need to get uint8_t values to uint32_t.
I can do this with shifting but i think there is a easy way.

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

    *v4full >>= 1;
}
printf("\n");
4
  • Can you show the construction of the source array?
    – bvj
    Commented Nov 30, 2013 at 3:38
  • sorry i corrected type error. source array construction in4_pton(token,-1,&v4,-1,&c); this converts a string into a ip address and put it in the v4 array Commented Nov 30, 2013 at 4:43
  • Okay. Don't cast the pointer in such a way the program thinks it's looking at a 32 bit word. If you need to work with int, iterate over the original vector of 8bit bytes, and then assign the byte to a simple int variable; e.g., for (int n=0; n < 4; n++) { int i = (int)v4[n]; ...} Unless you wish to present the entire vector as a combined 32bit word...
    – bvj
    Commented Nov 30, 2013 at 4:54
  • Just to clarify: can we think of v4 as uint8_t v4[4] and you want to get that as a single 32 bit number?
    – Floris
    Commented Nov 30, 2013 at 4:55

6 Answers 6

25

Given the need to get uint8_t values to uint32_t, and the specs on in4_pton()...

Try this with a possible correction on the byte order:

uint32_t i32 = v4[0] | (v4[1] << 8) | (v4[2] << 16) | (v4[3] << 24);
1
  • 1
    Your guess is as good as mine… if he needs byte order reversed, your answer is correct (giving a +1 just in case). If he doesn't, mine is marginally more compact. It might depend on the machine architecture (big/little endian…)
    – Floris
    Commented Nov 30, 2013 at 5:06
9

There is a problem with your example - actually with what you are trying to do (since you don't want the shifts).

See, it is a little known fact, but you're not allowed to switch pointer types in this manner

specifically, code like this is illegal:

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

The only case where this is legal is if type2 is char (or unsigned char or const char etc.), but if type2 is any other type (uint32_t in your example) it's against the standard and may introduce bugs to your code if you compile with -O2 or -O3 optimization.

This is called the "strict-aliasing rule" and it allows compilers to assume that pointers of different types never point to related points in memory - so that if you change the memory of one pointer, the compiler doesn't have to reload all other pointers.

It's hard for compilers to find instances of breaking this rule, unless you make it painfully clear to it. For example, if you change your code to do this:

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

and compile using -O3 -Wall (I'm using gcc) you'll get the warning:

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

So you can't avoid using the shifts.

Note: it will work on lower optimization settings, and it will also work in higher settings if you never change the info pointer to by v4 and v4_full. It will work, but it's still a bug and still "against the rules".

5

One other issue that makes this code non-portable is that many architectures require a uint32_t to be aligned on a four-byte boundary, but allow uint8_t to have any address. Calling this code on an improperly-aligned array would then cause undefined behavior, such as crashing the program with SIGBUS. On these machines, the only way to cast an arbitrary uint8_t[] to a uint32_t[] is to memcpy() the contents. (If you do this in four-byte chunks, the compiler should optimize to whichever of an unaligned load or two-loads-and-a-shift is more efficient on your architecture.)

If you have control over the declaration of the source array, you can #include <stdalign.h> and then declare alignas(uint32_t) uint8_t bytes[]. The classic solution is to declare both the byte array and the 32-bit values as members of a union and type-pun between them. It is also safe to use pointers obtained from malloc(), since these are guaranteed to be suitably-aligned.

4

If v4full is a pointer then the line

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

Should throw an error or at least a compiler warning. Maybe you mean to do

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

Where I assume v4 is itself a pointer to a uint8 array. I realize I am extrapolating from incomplete information…

EDIT since the above appears to have addressed a typo, let's try again.

The following snippet of code works as expected - and as I think you want your code to work. Please comment on this - how is this code not doing what you want?

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

Output:

the number is 04030201

Note - the order of the bytes in the printed number is reversed - you get 04030201 instead of 01020304 as you might have expected / wanted. This is because my machine (x86 architecture) is little-endian. If you want to make sure that the order of the bytes is the way you want it (in other words, that element [0] corresponds to the most significant byte) you are better off using @bvj's solution - shifting each of the four bytes into the right position in your 32 bit integer.

Incidentally, you can see this earlier answer for a very efficient way to do this, if needed (telling the compiler to use a built in instruction of the CPU).

7
  • Is it your impression the op wants to dereference the entire array as a pointer to a 32bit word?
    – bvj
    Commented Nov 30, 2013 at 4:56
  • But there's a potential byte-order issue given the v4 array is a binary representation of an IPv4 address.
    – bvj
    Commented Nov 30, 2013 at 5:09
  • 3
    Just FYI - technically allOfIt = (uint32_t*)v4 is illegal under the c99 standard. It may introduce bugs in the code either in the future, or even in current compilers on higher optimization.
    – rabensky
    Commented Nov 30, 2013 at 6:37
  • @cluracan I didn't know -my C is rather older than '99... I suppose you are still allowed a union of the two types? That would be a couple more lines of code...
    – Floris
    Commented Nov 30, 2013 at 12:55
  • @Floris Union still works AFAIK, but is also against the standard (because you'd be writing to one member and reading from another, which is technically not allowed in unions). Unfortunately, both C and C++ are moving in directions that prohibit any kind of "smart" low-level implementations (Another example I hate: signed overflow is undefined behaviour and not allowed :( ). I'm sure they have their reasons, but I don't like it :(
    – rabensky
    Commented Nov 30, 2013 at 16:10
0

This is one solution:

/* 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;
}
-1

One more solution:

u32 ip;

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

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

Here we use result of in4_pton function (ip) without any additional variables and castings.

2
  • 3
    Please explain what your code does and why it will solve the problem. An answer that just contains code (even if it's working) usually wont help the OP to understand their problem. Commented Aug 6, 2015 at 17:13
  • @SuperBiasedMan: See second comment to the question - user2714949 ask the question in according to use result of in4_pton. My answer is another approach to use this function without additional variables and castings.
    – dimcha
    Commented Aug 7, 2015 at 5:27

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.