Python Numeric series-Binary conversion

Source: Internet
Author: User

286 binary integer Problem

You need to convert or output integers that use binary, octal, or hexadecimal notation.

Solution Solutions

To convert an integer to a binary, octal, or hexadecimal text string, you can use it bin() , or a oct() function, respectively hex() :

 >>> x = 1234> >> bin (x)  0b10011010010 ' >>> hex (x< Span class= "P" >)  ' 0x4d2 ' >>>        

Also, if you do not want to output  0b  , 0o   or   0x   prefix, you can use  format ()   functions. For example:

Format(x' B ')' 10011010010 'format(x' o ')' 2322 'format( x 'x ')' 4d2 '>>>            

Integers are signed, so if you are dealing with negative numbers, the output will contain a minus sign. Like what:

-1234Format(x' B ') '-10011010010 'format(x' x ')' -4d2 ' >>>             

If you want to produce an unsigned value, you need to add a value that indicates the maximum bit length. For example, to display a 32-bit value, you can write as follows:

-1234format(2* *x' B ')' 11111111111111111111101100101110 'format  (2* *x 'x ')' fffffb2e '>>>         

In order to convert an integer string with a different binary, simply use the function with the binary int() :

int(' 4d2 ')1234int(' 10011010010 '2)1234>>> 
Discuss

In most cases, binary, octal, and hexadecimal integers are very simple to handle. Just remember that these conversions are conversions between integers and their corresponding text representations. There is always only one integer type.

Finally, programmers using octal have a point to pay attention to. Python specifies that the syntax for octal numbers differs slightly from other languages. For example, if you specify octal as follows, a syntax error occurs:

OSos.  chmod(' script.py '0755) File "<stdin>", line 1 os.chmod (' script.py ', 0755) ^ Syntaxerror:invalid token>>>           

Be sure to prefix the octal number 0o as follows:

Os.  chmod(' script.py '0o755)>>>       

Python Numeric series-Binary conversion

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.