-3

How can I read and extract specific number of bits of a 32-bit unsigned integer in C++/C? Then, resulted values convert to floating point.

For example: 32 integer 0xC0DFCF19 for x=read 11 bits, y=read 11 bits and for z = read last 10 bits of 32 bit integer. Thanks in advance!

Okay! Thanks a lot for all answers, very helpful!

Could someone give an example code how to read this integer 0x7835937C in the similar way, but "y" should be 334 (x,z remains the same) Thanks

Andrew
  • 15
  • 1

2 Answers2

0

The general idea is to mask part of the bits using bitwise boolean operations and the shift operator >> to move the bits to the desired location. Specifically the & operator allows you to let specific bits as they are, and set all others to zero. As in your example for y you need to mask bits 11-21 from the 32 bits of the input like in:

input  xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
& with 00000000000111111111110000000000
=      00000000000xxxxxxxxxxx0000000000
shift by 10 bits to the right
=      000000000000000000000xxxxxxxxxxx

Since you cannot write bits in C style, you have to convert the bitmask to hex.

The conversion to floating point is handled inplicitly, when you assign it a double or float variable, assuming you want to convert the integer-value (e.g. 5) to floating point (e.g. 5.0).

Assuming that your bits are partitioned as

xxxxxxxxxxxyyyyyyyyyyyzzzzzzzzzz

and you want double results your example would then be as following:

int v = 0; //input
double x = v >> 21;
double y = (v & 0x1FFC00) >> 10;
double z = v & 0x3FF;
azt
  • 2,100
  • 16
  • 25
0

Here is a demonstrative program

#include <iostream>
#include <iomanip>
#include <cstdint>

int main() 
{
    std::uint32_t value = 0xC0DFCF19;
    std::uint32_t x = value & 0x7FF;
    std::uint32_t y = ( value & ( 0x7FF << 11 ) ) >> 11;
    std::uint32_t z = ( value & ( 0x3FF << 22 ) ) >> 22;

    std::cout << "value = " << std::hex << value << std::endl;
    std::cout << "x = " << std::hex << x << std::endl;
    std::cout << "y = " << std::hex << y << std::endl;
    std::cout << "z = " << std::hex << z << std::endl;

    return 0;
}

The program output is

value = c0dfcf19
x = 719
y = 3f9
z = 303

You may declare variables x, y, z like floats if you need.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335