bit programming -> take out the bit at odd/even index

Assumed we have a uint16_t as 1100110011001100
How can I take out the bit at odd or even index, then return a uint8_t, since half of the input.

1
2
3
  uint16_t bits = 0b 1100110011001100;
  takeout_odd(bits);
  takeout_even(bits);  // both are 10101010 
Last edited on
Edited to get odd and even bits the right way round (I think!)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <cstdint>
#include <bitset>
using namespace std;

uint8_t evenBits( uint16_t big )
{
   uint8_t small = 0;
   for ( int p = 0, q = 0; p < 8; p++, q += 2 ) small |= ( big & ( 1 << q ) ) >> p;
   return small;
}

uint8_t oddBits( uint16_t big )
{
   return evenBits( big >> 1 );
}

int main()
{
   uint16_t bits = 0b1100110011001100;         // bit 15, 14, ..., 1, 0

   cout << bitset<8>( evenBits( bits ) ) << '\n';
   cout << bitset<8>( oddBits( bits ) ) << '\n';
}




Here's another:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <cstdint>
#include <bitset>
using namespace std;

uint8_t evenBits( uint16_t big )
{
   uint8_t small = 0;
   for ( uint8_t power = 1; big; big >>= 2, power <<= 1 ) if ( big % 2 ) small += power;
   return small;
}

uint8_t oddBits( uint16_t big )
{
   return evenBits( big >> 1 );
}

int main()
{
   uint16_t bits = 0b1100110011001100;         // bit 15, 14, ..., 1, 0

   cout << bitset<8>( evenBits( bits ) ) << '\n';
   cout << bitset<8>( oddBits( bits ) ) << '\n';
}
Last edited on
or think about it for a bit ;)
you want to grab every other bit into an int.
going backwards seems reasonable...
set your target value to zero.
peel off the last bit in the number (its 0) and add times 2 to the power of your loop increment (starting at zero). 2 to the zero is 1, 0 * 1 is zero, add zero.
shift the input twice to the right.
repeat, … peel off the 1, multiply by 2 to the 1 (2) and add (2) .. current value in binary is 2 = 00000000000010
and keep looping for all the bits in a uint16_t.

which is probably what was shown in code, broken down in to your precoding 'how would I do that' steps.

the powers of 2 are just int p2 = 1; and every loop do p2*=2. Or shift it once, if you are feeling the bit operations.

Last edited on
Topic archived. No new replies allowed.