This article mainly introduces how to use Python built-in modules and functions to convert numbers in different hexadecimal formats. Python also makes it very convenient to read pure binary files. For more information, see
Binascii module:
It contains a function that converts binary values into hexadecimal values, which can also be converted in turn. # Binary_value is a binary value, not a string or 1010 of the int type.
Binascii. b2a_hex (binary_value) # binary_value can be obtained by reading binary files> '89'
Builtin functions provided by python:
Bin (num) decimal value ===" binary string
bin(10) >> '0b1010'
Oct (num) decimal value ===" octal string
oct(10) >>'012'
Hex (num) decimal value ===" hexadecimal string
hex(20) >>'0x14'
Int (str, base) Other hexadecimal string = "decimal value. base indicates the hexadecimal value of str. If it is 2, str is binary, the default base is decimal.
int('20') >>20
int('10', 2) >>2
int('10', 8) >>8
int('20', 10) >>20
int('20',16) >>32
Character and number conversion functions:
Chr (int) integer to character
chr(65) >>'A',
Ord (chr) character to integer
ord('a') >>97,
Finally, an example of reading the binary content of an image file is provided:
#! /Usr/bin/env python # encoding: UTF-8 import binascii fh = open (r 'C: \ Temp \ img \ 2012517165556.png ', 'rb') a = fh. read () # print 'raw: ', 'A', type (a) hexstr = binascii. b2a_hex (a) # obtain a hexadecimal number # print 'hex: ', hexstr, type (hexstr) bsstr = bin (int (hexstr, 16) [2:] print 'bin: ', bsstr, type (bsstr)
Why is the screen-flushing effect a little tricky?