Conversion between Python's various binaries

Source: Internet
Author: User
Tags binary to decimal

Represents the symbols for each binary:
B: Binary, O: octal, D: Decimal, x: Hex
The Bin (), Oct (), Hex () return values are strings and are prefixed with 0b, 0o, and 0x, respectively.
1, decimal turn binary

>>> bin(10)‘0b1010‘>>> ‘{0:b}‘.format(10)‘1010‘

Both of these methods return a binary string representation.
Direct binary binary to decimal number

list1 = []ifnum1andnum0:  "二进制:%d" %(num)else :  whilenum1 :    list1.append(str(num2))    num2  list1.append(str(num))  list1.reverse()

2, decimal turn octal

>>> oct(12)‘014‘>>> ‘{0:o}‘.format(12)‘14‘

3, decimal turn hex

>>> hex(12)‘0xc‘>>> ‘{0:x}‘.format(12)‘c‘

4. Binary decimal

>>> int(‘1010‘,2)10>>> eval(‘0b10‘)2

int (string_num, N):
String_num: string representation of the binary
N: Indicates how many string_num the number of binary
5, octal decimal

>>> int(‘014‘,8)12>>> ‘{0:d}‘.format(014)‘12‘>>> eval(‘0o10‘)8

6, hexadecimal to decimal

>>> ‘{0:d}‘.format(0xc)‘12‘>>> int(‘0xc‘,16)12>>> eval(‘0x10‘)16

Note:
The hex function is slower than the format string function and is not recommended for use.
The Eval function is slower than the INT function and is not recommended for use.

Binary, 16, octal conversion between, you can use the decimal value, that is, the first to go to the decimal and then to other binary, you can also directly using the function to convert. Such as:
Hex Turn binary:

#借助十进制>>> bin(int(‘fc‘,16))‘0b11111100‘#利用函数直接转>>> bin(0xa)‘0b1010‘>>> oct(0xa)‘012‘>>> hex(10)‘0xa‘

Copyright NOTICE: This article for Bo Master original article, can be reproduced, but must indicate the source. More articles please follow the public number: Gloryroadtrain

Conversion between Python's various binaries

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.