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

Asked

Viewed 323 times

-3

I need to create two functions

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

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

How could I possibly do that? I had some ideas, but I didn’t come to any conclusions that worked, thanks in advance.

  • 1

    See if this helps: https://answall.com/q/201392/101. Here: https://answall.com/q/190575/101

  • 2

    It would be good [Dit] and describe at least what you tried and what difficulty you found, so it gives at least to have an idea of what you know and what you need to know to arrive at the intended result. Posts that give the impression of "do everything for me" are usually not well accepted, even if it is unintentional.

  • 1

    Thanks for the attention Maniero and Bacco, thanks for the tip,fortunately the friend replied,I will try to be careful with this in the next questions,thanks =D

2 answers

1


Use the bitwise logical operators to get 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 with the amount of bits to be removed:

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

0

Very simple, I’ll give the example of 32-bit integer, but you can easily apply in a short int. First for you to catch the low order, just you do it:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.