Skip to content

Commit 5aa2fb0

Browse files
authored
Merge pull request keon#58 from ofek/bytes-int-conversion
add bytes <-> int conversion
2 parents 7a67d6e + 9426432 commit 5aa2fb0

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-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: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
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+
13+
def int_to_bytes_little_endian(num):
14+
bytestr = []
15+
while num > 0:
16+
bytestr.append(num & 0xff)
17+
num >>= 8
18+
return bytes(bytestr)
19+
20+
21+
def bytes_big_endian_to_int(bytestr):
22+
num = 0
23+
for b in bytestr:
24+
num <<= 8
25+
num += b
26+
return num
27+
28+
29+
def bytes_little_endian_to_int(bytestr):
30+
num = 0
31+
e = 0
32+
for b in bytestr:
33+
num += b << e
34+
e += 8
35+
return num

0 commit comments

Comments
 (0)