python 進製 轉換

2022-07-18 13:45:21 字數 2202 閱讀 2584

測試用的python原始碼

[python]view plain

copy

''''' 

created on 2023年8月21日 

@author: lenovo 

'''  

import binascii  

import struct  

def example(express, result=none):  

if result == none:  

result = eval(express)  

print(express, ' ==> ', result)  

if __name__ == '__main__':  

print('整數之間的進製轉換:')  

print("10進製轉16進製制", end=': ');example("hex(16)")  

print("16進製制轉10進製", end=': ');example("int('0x10', 16)")  

print("類似的還有oct(), bin()")  

print('\n-------------------\n')  

print('字串轉整數:')  

print("10進製字串", end=": ");example("int('10')")  

print("16進製制字串", end=": ");example("int('10', 16)")  

print("16進製制字串", end=": ");example("int('0x10', 16)")  

print('\n-------------------\n')  

print('位元組串轉整數:')  

print("轉義為short型整數", end=": ");example(r"struct.unpack('

print("轉義為long型整數", end=": ");example(r"struct.unpack('

print('\n-------------------\n')  

print('整數轉位元組串:')  

print("轉為兩個位元組", end=": ");example("struct.pack('

print("轉為四個位元組", end=": ");example("struct.pack('

print('\n-------------------\n')  

print('字串轉位元組串:')  

print('字串編碼為位元組碼', end=": ");example(r"'12abc'.encode('ascii')")  

print('數字或字元陣列', end=": ");example(r"bytes([1,2, ord('1'),ord('2')])")  

print('16進製制字串', end=': ');example(r"bytes().fromhex('010210')")  

print('16進製制字串', end=': ');example(r"bytes(map(ord, '\x01\x02\x31\x32'))")  

print('16進製制陣列', end =': ');example(r'bytes([0x01,0x02,0x31,0x32])')  

print('\n-------------------\n')  

print('位元組串轉字串:')  

print('位元組碼解碼為字串', end=": ");example(r"bytes(b'\x31\x32\x61\x62').decode('ascii')")  

print('位元組串轉16進製表示,夾帶ascii', end=": ");example(r"str(bytes(b'\x01\x0212'))[2:-1]")  

print('位元組串轉16進製表示,固定兩個字元表示', end=": ");example(r"str(binascii.b2a_hex(b'\x01\x0212'))[2:-1]")  

print('位元組串轉16進製制陣列', end=": ");example(r"[hex(x) for x in bytes(b'\x01\x0212')]")  

print('\n***************====\n')  

print("以上原理都比較簡單,看一下就明白了。這裡僅僅是拋磚引玉,有更好更簡單的方法,歡迎歡迎")  

Python 進製轉換

python 進製轉換 1 oct hex bin 允許把 整數轉換為其他進製的字串 例子 oct 64 hex 64 bin 64 0100 0x40 0b1000000 oct函式會將十進位制數轉換為八進位制數,hex函式會將十進位制數轉換為十六進製制數,而 bin函式會將十進位制轉換為二進位制...

Python 進製轉換

python手擼實現十進位制轉16 8 2進製 class solution object def init self pass def convert self while true input num input 請輸入乙個整數 輸入q結束程式 if input num q return ten...

Python 進製轉換

print bin 4 輸出0b100 print format 4 輸出100print oct 8 輸出0o10 print format 8 輸出10print hex 15 輸出0xf print format 15 輸出f int 要轉換的字串 制定進製 print int 1010 2 ...