]> gitweb.pimeys.fr Git - NK2015_Client_Python_Alpha.git/blob - rsa_source/rsa/common.py
on ajoute le module rsa car le client aussi en a besoin
[NK2015_Client_Python_Alpha.git] / rsa_source / rsa / common.py
1 # -*- coding: utf-8 -*-
2 #
3 # Copyright 2011 Sybren A. Stüvel <sybren@stuvel.eu>
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17 '''Common functionality shared by several modules.'''
18
19
20 import math
21
22 def bit_size(number):
23 '''Returns the number of bits required to hold a specific long number.
24
25 >>> bit_size(1023)
26 10
27 >>> bit_size(1024)
28 11
29 >>> bit_size(1025)
30 11
31
32 >>> bit_size(1 << 1024)
33 1025
34 >>> bit_size((1 << 1024) + 1)
35 1025
36 >>> bit_size((1 << 1024) - 1)
37 1024
38
39 '''
40
41 if number < 0:
42 raise ValueError('Only nonnegative numbers possible: %s' % number)
43
44 if number == 0:
45 return 1
46
47 # This works, even with very large numbers. When using math.log(number, 2),
48 # you'll get rounding errors and it'll fail.
49 bits = 0
50 while number:
51 bits += 1
52 number >>= 1
53
54 return bits
55
56
57 def byte_size(number):
58 """Returns the number of bytes required to hold a specific long number.
59
60 The number of bytes is rounded up.
61
62 >>> byte_size(1 << 1023)
63 128
64 >>> byte_size((1 << 1024) - 1)
65 128
66 >>> byte_size(1 << 1024)
67 129
68 """
69
70 return int(math.ceil(bit_size(number) / 8.0))
71
72 if __name__ == '__main__':
73 import doctest
74 doctest.testmod()
75