Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I extract digit in an integer using bitwise operator

Tags:

c++

c

bit-shift

How do I extract digits from an integer using bitwise operator. i.e. I want to extract 234 in the integer n=123456 I know this is possible using and, or, xor bitwise operator but I'm not sure How? thnx

like image 306
hlim Avatar asked Sep 18 '25 09:09

hlim


2 Answers

If you don't want bitwise at this point, I believe you can extract individual digits like this:

int digitAtPos(int number, int pos)
{
   return ( number / (int)pow(10.0, pos-1) ) % 10;
}

I'm not sure if this is the fastest/most-efficient way, but it works.

Stitching the digits back together should be easy as well, just multiply by increasing powers of ten.

If anyone has a better solution, please tell.

like image 112
rcplusplus Avatar answered Sep 20 '25 01:09

rcplusplus


Since this is tagged as homework, i'm only going to explain basic concepts, I'm not actually going to produce an answer.

You use bitwise operations to extract individual bits of a base 2 number. So if your number is 10110101, and you want to get the 0101 at the end, you would have to set up a mask, and then do a binary anding to filter out the unimportant digits. Your mask should look something like 00001111. When you and them together, only the digits you want are remaining.

10110101 & 00001111 == 00000101

like image 30
Sam I am says Reinstate Monica Avatar answered Sep 19 '25 23:09

Sam I am says Reinstate Monica