2020年6月30日 星期二

Binary Data, String, and Integer Conversions in Python

In Python 3, struct will interpret bytes as packed binary data:
This module performs conversions between Python values and C structs represented as Python bytes objects. This can be used in handling binary data stored in files or from network connections, among other sources.
>>> import struct >>> struct.pack("<HH", 2, 8) b'\x02\x00\x08\x00'
>>> struct.pack("BB", 0x31, 0x32) b'12' >>> "12" '12'
There is no "bytes" type in Python 2. In Python 2, struct will interpret bytes as strings:
This module performs conversions between Python values and C structs represented as Python strings. This can be used in handling binary data stored in files or from network connections, among other sources.
>>> bytes is str
True
>>> struct.pack("<HH", 2, 8)'\x02\x00\x08\x00'
>>> struct.pack("<BB", 0x31, 0x32)'12'>>> "12"'12'

In Python 3,

int.to_bytes(length, byteorder, *, signed=False) will return an array of bytes representing an integer.
>>> a=0x1122334455
>>> b=a.to_bytes(5, byteorder="little")
>>> b.hex()
'5544332211'

int.from_bytes(bytes, byteorder, *, signed=False) will return the integer represented by the given array of bytes.
>>> c = int.from_bytes(b, byteorder="little") >>> hex(c) '0x1122334455'
If the integer is within 0~255, you can also use "bytes":
>>> bytes([0x11])
b'\x11'
I couldn't find the built-in method to convert long integer to bytes in Python 2. You can use "binascii" module instead.


String converts to bytes:
>>> s="123456"
>>> s.encode()
b'123456'
Integer converts to String
>>> s=hex(a)
>>> s
'0x1122334455'
binascii --- converts between binary and ASCII (string)

binascii.b2a_hex(data)
binascii.hexlify(data)
binascii.a2b_hex(hexstr)
binascii.unhexlify(hexstr)
binascii.crc32(data[, value])

2020年3月2日 星期一

C++ Debug on VS code for Linux


  • Install C/C++ Extension for VS Code
  • Select the working directory: in VS Code, File->Open Folder, select the directory for your code files.
  • Edit tasks.json to compile the code: 
          In the command pallete (Ctrl+Shift+p), type the following to add "tasks.json" file to the project
          > Tasks: Configure Task
          > click Create tasks.json file from templates
          > select Others.

          Edit "label" and "commands" in tasks.json, here's the example:


        Note: for GCC debug, -g option should be included to tell the compiler to generate extra info for debugging

  • Modify launch.json to debug your code

          Go to Debug -> Start Debugging, it will open the launch.json file.
          Modify "program" tag and add "preLaunchTask" as the following example.


That's it. You can start debugging now...





Binary Data, String, and Integer Conversions in Python

In Python 3, struct  will interpret bytes as packed binary data: This module performs conversions between Python values and C structs rep...