Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to extract ODD digits from a binary number

Given a 64 bit number, I need to extract every other bit from it, and convert it into a number:

decimal:  357
binary:   0000 0001 0110 0101
odd bits:  0 0  0 1  1 0  1 1
decimal:  27

Any idea of a good algorithmic way to do it? And no, not HW, this is for a real world use :)

like image 420
Yuri Astrakhan Avatar asked Jun 16 '15 02:06

Yuri Astrakhan


Video Answer


1 Answers

I would go with performing Arithmetic Right Shift(till the length of the binary number) two at a time. This >> used in my logic is for arithmetic shift.

(Note: In C language, right shifts may or may not be arithmetic!)

Like,

int count=0;
bit=extractLastbit(binary_representation_of_the_number);

while(count!=binaryLength){
  // binaryLength is the length of the binary_representation_of_the_number
  binary_representation_of_the_number=binary_representation_of_the_number>>2;

  bit.appendLeft(extractLastbit(binary_representation_of_the_number);
  count=count+2;
}

where,

extractLastBit() extracts the LSB of the binary number; appendLeft() performs shifting the newly extracted bit to the left of the older bit(s).

like image 145
Am_I_Helpful Avatar answered Nov 15 '22 10:11

Am_I_Helpful