简体   繁体   中英

How to cast uint8* to uint32

When writing:

uint8_t var_a[4] = {0, 255, 0, 255};

I expect the memory layout to be:

00000000111111110000000011111111

But when casting to uint32:

cout << *(uint32_t*)var_a;

it returns 4278255360, which is the reverse

11111111000000001111111100000000

How does this work?

You got the memory layout you expected. However, when you read the memory as a uint32_t , the system interpreted it according to how it lays out 32-bit values in memory. Your system appears to lay out 32-bit values in 8-bit memory addresses by putting the least significant bytes first.

Say I have a piece of paper with four boxes in it. I can write the number one thousand four hundred and twelve as either "1,4,1,2" or "2,1,4,1". There's no particular reason to prefer one over the other just because humans normally right digits from left to right.

If you're going to place numbers in each of those four boxes yourself and then ask me what four-digit number that represents, you have to know which box I'm using for which digit. You can't just assume I'm using left to right.

Your computer happens to store the least significant bytes at the lower memory addresses. There's no particular reason to prefer one method over the other.

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