Bonjour,
j'ai besoin de faire une rotation par la droite sur un groupe de bits. J'ai codé une fonction pour le faire, mais j'aimerai savoir si il y a pas plus simple. Il me semble que je dois faire beaucoup de conversions (transformation en string puis retour en binaire).
Je suis aussi preneur pour toutes optimisations, ou amélioration du code (bonnes pratiques...)
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27 def rotate_right(value, rotate, lenght): # basic case if (rotate == 0): return value # convert value in binary binary_value = bin(value) binary_value = binary_value[2:] # cut the 0b len_binary = len(binary_value) # error, we want a size inferior than if (len_binary > lenght): raise("Size of new value smaller than original value") return None # padding with 0 and concat the value list = [] for i in range(lenght-len_binary): list.append("0") list.append(binary_value) binary_value = ''.join(list) # rotate binary_value = binary_value[lenght-rotate:] + binary_value[:lenght-rotate] return int(binary_value,2)
Merci de votre aide
p.s. je travaille en python 2.7
Partager