summaryrefslogtreecommitdiff
path: root/rsa/common.py
diff options
context:
space:
mode:
authorSybren A. Stüvel <sybren@stuvel.eu>2016-03-29 19:45:47 +0200
committerSybren A. Stüvel <sybren@stuvel.eu>2016-03-29 19:46:15 +0200
commit5e08c91a122bac2e59e176928aa1b24f9aa7b0b2 (patch)
tree9f17a9cc17f3da59eef408895d7fba64e37ba61d /rsa/common.py
parent9a9e08ce6559f888c345935bac7f85f747fc5f06 (diff)
downloadrsa-git-5e08c91a122bac2e59e176928aa1b24f9aa7b0b2.tar.gz
No longer require string operations to find bit lengths.
Now that we no longer support Python 2.6, we can use int.bit_length() instead. Co-authored by @adamantike.
Diffstat (limited to 'rsa/common.py')
-rw-r--r--rsa/common.py41
1 files changed, 4 insertions, 37 deletions
diff --git a/rsa/common.py b/rsa/common.py
index 34142cc..4f8c0d9 100644
--- a/rsa/common.py
+++ b/rsa/common.py
@@ -31,9 +31,6 @@ def bit_size(num):
Number of bits needed to represent a integer excluding any prefix
0 bits.
- As per definition from https://wiki.python.org/moin/BitManipulation and
- to match the behavior of the Python 3 API.
-
Usage::
>>> bit_size(1023)
@@ -50,41 +47,11 @@ def bit_size(num):
:returns:
Returns the number of bits in the integer.
"""
- if num == 0:
- return 0
- if num < 0:
- num = -num
-
- # Make sure this is an int and not a float.
- num & 1
-
- hex_num = "%x" % num
- return ((len(hex_num) - 1) * 4) + {
- '0': 0, '1': 1, '2': 2, '3': 2,
- '4': 3, '5': 3, '6': 3, '7': 3,
- '8': 4, '9': 4, 'a': 4, 'b': 4,
- 'c': 4, 'd': 4, 'e': 4, 'f': 4,
- }[hex_num[0]]
-
-
-def _bit_size(number):
- """
- Returns the number of bits required to hold a specific long number.
- """
- if number < 0:
- raise ValueError('Only nonnegative numbers possible: %s' % number)
-
- if number == 0:
- return 0
-
- # This works, even with very large numbers. When using math.log(number, 2),
- # you'll get rounding errors and it'll fail.
- bits = 0
- while number:
- bits += 1
- number >>= 1
- return bits
+ try:
+ return num.bit_length()
+ except AttributeError:
+ raise TypeError('bit_size(num) only supports integers, not %r' % type(num))
def byte_size(number):