13 กันยายน 2561

Published กันยายน 13, 2561 by with 0 comment

ภาษาไพทอนกับเลขฐานสิบ ฐานสอง ฐานแปด ฐานสิบหก

ตัวดำเนินการ
~ Not
^ XOR
| Or
& And

แปลงเลขฐานสอง เป็น ฐานสิบ


>>> 0b101111
47

หรือ
>>> print(int('01010101111',2))
687
>>> print(int('11111111',2))
255





แปลงเลขฐานสิบ เป็น ฐานสอง


ใช้คำสั่ง bin(เลขฐานสิบ จำนวนเต็ม)
>>> bin(173)
'0b10101101'





รับ list ทั้งหมดของ ascii ใน python
ascii characters
>>> import string
>>> string.ascii_uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

รับ printable characters ทั้งหมด
>>> string.printable
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;?@[\\]^_`{|}~ \t\n\r\x0b\x0c'





คำสั่ง ord()
function ord() would get the int value of the char. And in case you want to convert back after playing with the number, function chr() does the trick.
>>> ord('a')
97
>>> chr(97)
'a'
>>> chr(ord('a') + 3)
'd'
>>>

chr() คืนค่าเป็น Unicode string




แปลงสตริง UTF 8 เป็น ASCII


>>> 'hi'.encode('ascii')
b'hi' 

แปลงข้อความ ASCII ที่เข้ารหัส Hex กลับมาเป็นสตริง


>>> import codecs
>>> codecs.decode("7061756c", "hex")
b'paul'
>>> str(codecs.decode("7061756c", "hex"))
"b'paul'"
>>> a= codecs.decode("7061756c", "hex")
>>> a.decode('utf-8')
'paul'

มีสตริงที่ถูกเข้ารหัส Hex เช่น
3C 4D 76 77 61 66

ต้องการแปลงกลับมาเป็นสตริงเช่นเดิม
>>> import binascii
>>> binascii.unhexlify('3C 4D 76 77 61 66')
Traceback (most recent call last):
  File "", line 1, in 
TypeError: Odd-length string
>>> binascii.unhexlify(''.join('3C 4D 76 77 61 66'.split()))
'<Mvwaf'

0 ความคิดเห็น:

แสดงความคิดเห็น

แสดงความคิดเห็นได้ครับ :)