File tree Expand file tree Collapse file tree 2 files changed +36
-0
lines changed
Expand file tree Collapse file tree 2 files changed +36
-0
lines changed Original file line number Diff line number Diff 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 )
Original file line number Diff line number Diff line change 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
You can’t perform that action at this time.
0 commit comments