Skip to content

Commit d5f4ff0

Browse files
committed
complete bytes <-> int functions
1 parent 7a67d6e commit d5f4ff0

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ Minimal and clean example implementations of data structures and algorithms in P
3838
- [shortest_distance_from_all_buildings](bfs/shortest_distance_from_all_buildings.py)
3939
- [word_ladder](bfs/word_ladder.py)
4040
- [bit](bit)
41+
- [bytes_int_conversion](bit/bytes_int_conversion.py)
4142
- [count_ones](bit/count_ones.py)
4243
- [power_of_two](bit/power_of_two.py)
4344
- [reverse_bits](bit/reverse_bits.py)

bit/bytes_int_conversion.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
from collections import deque
2+
3+
4+
def int_to_bytes_big_endian(num):
5+
bytestr = deque()
6+
while num > 0:
7+
# list.insert(0, ...) is inefficient
8+
bytestr.appendleft(num & 0xff)
9+
num >>= 8
10+
return bytes(bytestr)
11+
12+
def int_to_bytes_little_endian(num):
13+
bytestr = []
14+
while num > 0:
15+
bytestr.append(num & 0xff)
16+
num >>= 8
17+
return bytes(bytestr)
18+
19+
def bytes_big_endian_to_int(bytestr):
20+
num = 0
21+
for b in bytestr:
22+
num <<= 8
23+
num += b
24+
return num
25+
26+
def bytes_little_endian_to_int(bytestr):
27+
num = 0
28+
e = 0
29+
for b in bytestr:
30+
num += b << e
31+
e += 8
32+
return num

0 commit comments

Comments
 (0)