简体   繁体   中英

Convert char array to int in C

Is this a safe way to convert array to number?

// 23 FD 15 94 -> 603788692
char number[4] = {0x94, 0x15, 0xFD, 0x23};
uint32_t* n = (uint32_t*)number;
printf("number is %lu", *n);

MORE INFO

I'm using that in a embedded device with LSB architecture, does not need to be portable. I'm currently using shifting, but if this code is safe i prefer it.

No, it is not safe.

This is violating C aliasing rules that say that an object can only be accessed trough its own type, its signed / unsigned variant or through a character type. It can also invoke undefined behavior by breaking alignment.

A safe solution to get a uint32_t value from the array is to use bitwise operators ( << and & ) on the char values to form an uint32_t .

No. You're only allowed to access something as an integer if it is an integer.

But here's how you can manipulate the binary representation of an object by simply turning the logic around:

uint32_t n;

unsigned char * p = (unsigned char *)&n;

assert(sizeof n == 4);    // assumes CHAR_BIT == 8

p[0] = 0x94; p[1] = 0x15; p[2] = 0xFD; p[3] = 0x23;

The moral: You can treat every object as a sequence of bytes, but you can't treat an arbitrary sequence of bytes as any particular object.

Moreover, the binary representation of a type is very much platform dependent , so there's no telling what actual integer value you get out from this. If you just want to synthesize an integral value from its base-256 digits, use normal maths:

uint32_t n = 0x94 + (0x15 * 0x100) + (0xFD * 0x10000) + (0x23 * 0x1000000);

This is completely platform-independent and expresses what you want purely in terms of values , not representations. Leave it to your compiler to produce a machine representation of the code.

You're better off with something like this (more portable):

int n = (c[3]<<24)|(c[2]<<16)|(c[1]<<8)|c[0];

where c is an unsigned char array.

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