Handmade Hero»Forums»Code
Albert
8 posts
None
[Day 025] Cast to DWORD to get low 32 bits
At 02:02:00 of https://hero.handmade.network/episode/win32-platform/day025, it's commented that direct casting may cause the compiler to "round" to the closest uint32, instead of picking up low 32bits solely.

However, according to C11:

1. When a value with integer type is converted to another integer type other than _Bool, if the value can be represented by the new type, it is unchanged.
2. Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.

Therefore, casting solely is sufficient here.

```
#include <stdio.h>
#include <stdint.h>
#include <limits.h>


int main(int argc, char *argv[])
{
uint64_t x = ((uint64_t)1 << 32) + 1;
uint32_t y = (uint32_t) x;
printf("%lu\n", x);
printf("%u\n", UINT_MAX);
printf("%u\n", y);
return 0;
}
```

prints:

```
4294967297
4294967295
1
```
Mārtiņš Možeiko
2565 posts / 2 projects
[Day 025] Cast to DWORD to get low 32 bits
Edited by Mārtiņš Možeiko on
Yes, for unsigned numbers that is how it works - it does "implict AND". In C89 this is defined like this:

When an integer is demoted to an unsigned integer with smaller size, the result is the nonnegative remainder on division by the number one greater than the largest unsigned number that can be represented in the type with smaller size.

For signed numbers it implementation-defined behavior.

C89: When an integer is demoted to a signed integer with smaller size, or an unsigned integer is converted to its corresponding signed integer, if the value cannot be represented the result is implementation-defined.

C11: Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.