Communities

Writing
Writing
Codidact Meta
Codidact Meta
The Great Outdoors
The Great Outdoors
Photography & Video
Photography & Video
Scientific Speculation
Scientific Speculation
Cooking
Cooking
Electrical Engineering
Electrical Engineering
Judaism
Judaism
Languages & Linguistics
Languages & Linguistics
Software Development
Software Development
Mathematics
Mathematics
Christianity
Christianity
Code Golf
Code Golf
Music
Music
Physics
Physics
Linux Systems
Linux Systems
Power Users
Power Users
Tabletop RPGs
Tabletop RPGs
Community Proposals
Community Proposals
tag:snake search within a tag
answers:0 unanswered questions
user:xxxx search by author id
score:0.5 posts with 0.5+ score
"snake oil" exact phrase
votes:4 posts with 4+ votes
created:<1w created < 1 week ago
post_type:xxxx type of post
Search help
Notifications
Mark all as read See all your notifications »
Challenges

Post History

66%
+2 −0
Challenges Reverse the bits in a Byte

Python (3.6 and up), 32 bytes (unsigned integer I/O) lambda x:int(f'{x:08b}'[::-1],2) Input and output are int objects. This also reverses the bits in integers larger than 255, implicitly infer...

posted 8mo ago by Karl Knechtel‭

Answer
#1: Initial revision by user avatar Karl Knechtel‭ · 2023-09-05T22:43:58Z (8 months ago)
# Python (3.6 and up), 32 bytes (unsigned integer I/O)

```
lambda x:int(f'{x:08b}'[::-1],2)
```

Input and output are `int` objects. This also reverses the bits in integers larger than 255, implicitly inferring their bit length from the number of bits needed to write them (even if that isn't a multiple of 8). It will raise an exception if given a negative number as input.

## Python (3.6 and up), 44 bytes (byte I/O)

```
lambda x:bytes([int(f'{x[0]:08b}'[::-1],2)])
```

Input and output are both actual `bytes` objects. This uses new-style string formatting to produce the bit-pattern directly (and takes advantage of the fact that indexing a `bytes` in 3.x gives an integer value), and uses the `bytes` constructor to produce a valid `bytes` object as the result (In Python 3.x, `chr` produces a string, not `bytes`).