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