Use Python built-in modules and functions to convert numbers in different hexadecimal formats

Source: Internet
Author: User
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?

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.