0

If I am trying to get a specific range of bits (in decimal) at a specific range, is the best way to go about this leftshifting to the end index, and then right shifting back to the start index?

#pesudo-code:
    def group(aNumber,start, end):
        n = aNumber << 32 - n
        a = n >> end - start
        print(a) 
4
  • "trying to get a specific range of bits (in decimal) at a specific range" - what ??? Commented Aug 29, 2015 at 22:49
  • Sorry for the confusion. If I have an int, I would like to extract the group of binary numbers that represent a certain index of that int. e.g. 5000, if end = 3 and start = 2, the binary number output should be 50. e.g. 0110 0010 Commented Aug 29, 2015 at 22:51
  • That won't work. Because Python will automatically turn the int into a long (which is essentially unlimited in size, and only constrained by your memory), so you can never get rid of bits on the left. Eg, 5 << 64 = 92233720368547758080L. Keep in mind that integers in Python don't work like those in C. Commented Aug 29, 2015 at 22:53
  • Oh...could I do something similar in C? If possible? Commented Aug 29, 2015 at 22:55

2 Answers 2

1

You can do that in python, you're just not using the correct method. When you want to retrieve part of a number, the operation you're trying to accomplish is called masking.

And you do that with a mask: number & 0xF0 will retreive bits 4 to 7 (without moving them). So (number & 0xF0) >> 4 will retrieve bits 4 to 7, and shift them all the way to the right.

As for the mask, ((1 << end) - 1) - ((1 << start) - 1) should build a correct mask. So...

mask = ((1 << end) - 1) - ((1 << start) - 1)
result = (number & mask) >> start

Actually, since you shift to the right right after, you don't even have to mask out the bits below those you want, so this will work just as well:

mask = ((1 << end) - 1)
result = (number & mask) >> start
Sign up to request clarification or add additional context in comments.

1 Comment

Does this answer the question? I think the OP wanted a mask, but they wanted one in decimal, not in binary, like you've done. E.g. group(5000,2,3) = 50, which is not what your code does.
1

If you want to get from bit b0 a total of bn bits:

def getbits(x, b0, bn):
    return (x >> b0) & ((1 << bn) - 1)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.