Python hexadecimal conversion (read binary files only)

Source: Internet
Author: User

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 '<type STR>

Builtin functions provided by Python:

Bin (Num) decimal value ===" binary string

 
Bin (10)> '0b1010' <type, STR>

Oct (Num) decimal value ===" octal string

 
Oct (10)> '012' <type, STR>

Hex (Num) decimal value ===" hexadecimal string

 
Hex (20)> '0x14' <type, STR>

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 <type, int> int ('10', 2)> 2 <type, int> int ('10', 8)> 8 <type, int> int ('20', 10)> 20 <type, int> int ('20', 16)> 32 <type, int>

Character and number conversion functions:

CHR (INT) integer to character

 
CHR (65)> 'A', <type, STR>

Ord (CHR) character to integer

 
Ord ('A')> 97, <type, int>

Finally, an example of reading the binary content of an image file is provided:

#! /Usr/bin/ENV Python # encoding: utf-8import 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?

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.