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