0

Is there any elegant and shortest way how to do it?

unsigned char someInteger(int someInt) {
    // 00110110
    unsigned char type[7];
    type[7] = ((someInt >> 7) & 0x1);
    type[6] = ((someInt >> 6) & 0x1);
    type[5] = ((someInt >> 5) & 0x1);
    type[4] = ((someInt >> 4) & 0x1);
    type[3] = 0;
    type[2] = 0;
    type[1] = 0;
    type[0] = 0;
    return type; // 48
}

I'd like to have just 4th to 7th bit of the number.

Thanks a lot!

John Doe
  • 31
  • 2
  • 3
    Does this answer your question? [Reading top nibble and bottom nibble in a byte](https://stackoverflow.com/questions/5909911/reading-top-nibble-and-bottom-nibble-in-a-byte). `0b00110110 & 0xF0` => 48 – ggorlen Dec 29 '19 at 21:10
  • Even if we ignore, that this code doesn't compile, it's unclear what you are trying to do. 4th to 7th bit of what number? Do you want to extract 4 bits from a byte? – Lukas-T Dec 29 '19 at 21:11
  • 1
    Your code doesn't compile because the return type doesn't match what you're returning and `type[7]` is out of bounds. – Retired Ninja Dec 29 '19 at 21:12

1 Answers1

0

Elegant & shortest way to save only half of byte

You can use bitwise AND to set half of the bits to zero. For example:

unsigned char byte = 0b00110110;
unsigned char mask = (1 << CHAR_BIT / 2) - 1;
unsigned char half = byte & mask;

I'd like to have just 4th to 7th bit of the number.

Again, use AND with a bitmask:

unsigned char byte = 0b00110110;
unsigned char mask = 0b01001000;
unsigned char b_4_7 = byte & mask;
eerorika
  • 232,697
  • 12
  • 197
  • 326