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
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.
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
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