0

Is there a standard library way in python to get the equivalent of a number reading bits in reverse ? (Apart from converting to a string, reversing it, and converting back)


Example of expected behavior :

>>> reverse(20) # 20 = b10100
5 # 5 = b00101
>>> reverse(11) # 11 = b1011
13 # 13 = b1101

Current (slightly improved, still janky) solution :

def reverse(n):
    return int(bin(n)[:1:-1], 2)
ice-wind
  • 690
  • 4
  • 20
  • Are you using a constant number of bits? i.e all numbers are between 0-255 (8 bits), 0-65535 (16 bits) etc? – Nathan Wride Oct 20 '20 at 01:39
  • @NathanWride Yes, I'm exclusively handling 64 bit values ! – ice-wind Oct 20 '20 at 01:44
  • I don't think python has any particular a built-in "reverse bits" functionality. The easiest is probably the method you are already using and another method is to perform bitwise math to do it yourself. – Nathan Wride Oct 20 '20 at 01:47
  • @NathanWride I'm a complete novice in bitwise maths, how would you reverse it with that method ? – ice-wind Oct 20 '20 at 01:49
  • 5
    Is "bitwise endianness" a thing? I've only ever seen it refer to the order of the bytes in a multi-byte number. – CryptoFool Oct 20 '20 at 01:53
  • @Steve Well I'm not sure but the fact is the bits I'm decompressing somehow end up reversed, and I don't know how else to express that. 'reversing bits' sort of implies I want to turn 1s to 0s and vice-versa, which isn't the case – ice-wind Oct 20 '20 at 01:57
  • @superbrain Added to the post, thanks for the improvement – ice-wind Oct 20 '20 at 01:57
  • 1
    So this is now officially an XY problem. – superb rain Oct 20 '20 at 01:58
  • 3
    Are you sure the expected behaviour is what you want? Keep in mind that this way of "reversing" is lossy: `reverse(16) = 1` and `reverse(1) = 1` – harold Oct 20 '20 at 01:58
  • @Steve: It's not. Bit Twiddling Hacks [provides some ways of reversing bits in bytes and words](https://graphics.stanford.edu/~seander/bithacks.html#BitReverseObvious), but they're intended for fixed width C integer types; they don't translate nearly as nicely to arbitrary precision Python `int`s (and at no point is this implied to have anything to do with endianness). – ShadowRanger Oct 20 '20 at 02:00
  • 3
    @AmyLucyRose: Sounds like your decompression code is bad; the solution is to make it correct, not hack around the badness. As superb rain notes, this [is an XY problem](https://meta.stackexchange.com/q/66377/322040). – ShadowRanger Oct 20 '20 at 02:01
  • @ShadowRanger This is not an XY problem, because turns out the bits aren't even reversed ! Problem seems to be with byte endianness, which I know how to deal with. This was a bad test code problem (also known as the "I don't have any test code, because I don't even know what the code is supposed to do yet" problem). – ice-wind Oct 20 '20 at 02:09
  • This is what you get when you try to decode someone else's poorly documented compression format – ice-wind Oct 20 '20 at 02:09

0 Answers0