Download code

Jump to: navigation, search

Back to Binary_numeral_conversion_(Python)

Download for Windows: single file, zip

Download for UNIX: single file, zip, tar.gz, tar.bz2

binary.py

 1 # The authors of this work have released all rights to it and placed it
 2 # in the public domain under the Creative Commons CC0 1.0 waiver
 3 # (http://creativecommons.org/publicdomain/zero/1.0/).
 4 # 
 5 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 6 # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 7 # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 8 # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 9 # CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
10 # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
11 # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
12 # 
13 # Retrieved from: http://en.literateprograms.org/Binary_numeral_conversion_(Python)?oldid=19018
14 
15 hex2bin = {'0': '0000', '1': '0001', '2': '0010', '3': '0011', '4': '0100',
16  '5': '0101', '6': '0110', '7': '0111', '8': '1000', '9': '1001', 'a': '1010',
17  'b': '1011', 'c': '1100', 'd': '1101', 'e': '1110', 'f': '1111'}
18 def bin(n):
19     if n < 0:
20         return "-" + bin(-n)
21     # Build list of groups of four binary digits
22     s = [hex2bin[hexdigit] for hexdigit in ("%x" % n)]
23     # Merge list to single string and remove leading zeros
24     s = "".join(s).lstrip("0")
25     return s or "0"
26 if __name__ == "__main__":
27     for i in range(-50, 50):
28         assert i == int(bin(i), 2)


hijacker
hijacker
hijacker
hijacker