Follow me on Twitter to receive updates, free scripts and ongoing announcements!

Convert shortint to bits and bits to shortint

Written by Codes Tips on March 18, 2009 – 3:22 am -

A short int have 16 bits so we will need a vector of 16 bits:

short int bits[16]; // from 0 to 15

 

To convert a short int to bits you should divide the integer by 2 until he is 0. 

void ShortIntToBits(int x)
 
{
 
int nr=-1,k1;
 
for(k1=0;k1<=15;k1++)
 
bits[k1]=0;
 
while (x!=0)
 
{
 
nr++;
 
bits[nr]=x%2;
 
x=x/2;
 
}
 
}

To convert a vector of bits to shortint we should iterate to the vector of bits adding to integer a value that is 2(because we have bits) at power of the position of bit.

Here is an example that have a vector  of 15 bits.

short int BitsToShortInt()
 
{
 
short int k1,p=1,x=0;
 
 
 
for (k1=0;k1<=15;k1++)
 
{
 
x=x+bits[k1]*p;
 
p=p*2;
 
}
 
return x;
 
}

Tags: , ,
Posted in Algorithms | No Comments »