Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Given 2 16-bit ints, can I interleave those bits to form a single 32 bit int?

Tags:

c++

Whats the proper way about going about this? Lets say I have ABCD and abcd and the output bits should be something like AaBbCcDd.

unsigned int JoinBits(unsigned short a, unsigned short b) { }
like image 527
Josh Lake Avatar asked Feb 26 '23 14:02

Josh Lake


2 Answers

#include <stdint.h>

uint32_t JoinBits(uint16_t a, uint16_t b) {
  uint32_t result = 0;
  for(int8_t ii = 15; ii >= 0; ii--){
    result |= (a >> ii) & 1;
    result <<= 1;
    result |= (b >> ii) & 1;
    if(ii != 0){
      result <<= 1;
    }
  }
  return result;
}

also tested on ideone here: http://ideone.com/lXTqB.

like image 193
vicatcu Avatar answered Apr 29 '23 14:04

vicatcu


First, spread your bits:

unsigned int Spread(unsigned short x)
{
  unsigned int result=0;
  for (unsigned int i=0; i<15; ++i)
    result |= ((x>>i)&1)<<(i*2);
  return result;
}

Then merge the two with an offset in your function like this:

Spread(a) | (Spread(b)<<1);
like image 21
ltjax Avatar answered Apr 29 '23 14:04

ltjax