# Extracting the rightmost N bits of a double in C

I have some natural large number in double the size. I need to get the 30 right-most bits (of the inherent part). If it was intact, the operation was:

``````var & 0x3FFFFFFF
```

```

I can implement some functionality for this purpose, but I need some simple solution. There is one?

* editing:

All answers don't work for me. I will try to explain: for example, I have a double x = 9362446620820194.0000, the rightmost 30 bits of the integer part of this number is 957350626.

I could use uint64_t instead of double, but I need 32-bit support.

ps I mean simple binary representation, not machine (memory)

+3

source to share

Assuming 8-bit `unsigned char`

:

``````unsigned char const *p = (unsigned char const *)&var;
long rightmost30 = (p[sizeof(double) - 4] & 0x3F) << 24
|  p[sizeof(double) - 3] << 16
|  p[sizeof(double) - 2] << 8
|  p[sizeof(double) - 1];
```

```

Although you should actually take a look at the `frexp`

related functions as well.

+2

source

Casting:

``````float var = 0.2987647892;
uint32_t bit_repr = *(uint32_t *)&var;
uint32_t masked = bit_repr & 0x3FFFFFFF;
```

```
0

source

All Articles