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 :)
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With