How to isolate higher order bits and lower order bits in C / C ++?

-3

I need to create two functions

One receives an integer value and returns another containing only the 8 lowest-order bits of the original value, with the other bits set to zero.

The other receives an integer value and returns another containing only the 8 highest order bits of the original value, with the other bits set to zero.

How could this be done? I had some ideas, but I did not come to any conclusion that worked, thank you in advance.

    
asked by anonymous 11.01.2018 / 15:47

2 answers

1

Use bitwise logical operators to grab the bits you want. The idea is to use a mask number and apply it to a value to extract only the desirable bits (which are described in the mask).

uint16_t value = 0b0100110111010001;
uint16_t MSB = value & 0xFF00; // resulta em 0b0100110100000000
uint16_t LSB = value & 0x00FF; // resulta em 0b0000000011010001

In the case of the most significant bit (MSB), if you want to disable the right zeros left by the mask, just shift the amount of bits to be removed:

uint16_t MSB = (value & 0xFF00) >> 8; // resulta em 0b0000000001001101
    
11.01.2018 / 15:57
0

Very simple, I'll give the 32-bit integer example, but you can easily apply in an int short. First of all for you to get the low order, you just do this:

unsigned int numero = 350000; // Inteiro de 32 bits sem sinal;

numero = numero & ((1 << 16) - 1); // Pegando bits de baixa ordemo

cout << numero << endl; // Resultado 22320

// Pegando bits de alta ordem
numero = 350000

unsigned int mascara = 0xFFFF0000; // Definindo mascara, em hexa.

unsigned int bitsAltos = numero & mascara; // Resulta em 0b00000000000001010000000000000000

bitsAltos = bitsAltos >> 16; // Movendo os bits 16 casas para direita
// resulta em 0b00000000000000000000000000000101
cout << bitsAltos << endl; // Valor 5
    
13.01.2018 / 17:37