/etc/xgrid/agent/controller-password
and similar files.The code I put up is rather silly. It uses a hard-coded dict to translate bytes (in string rep) to hexadecimal. This is not worth spending too much time on, especially since Python 3 has a whole 'nother attitude about strings and bytes, but I thought I would at least show a simple and more correct (I hope) Python 2 approach to this issue.
So, of course we have bits and bytes on the machine, and strings exist only on-screen or paper. We can represent bits and bytes as integers, or as chars, and vice-versa. I'm sure everyone knows we can go from int to chr and back again:
My understanding is that we should view integers as the natural intermediate form for conversion of bits and bytes from base 2 to other bases.
In this representation the binary number
1111
is an int (15) or its string representation ('0b1111'). Python also has string reps for hexadecimal and octal:We can go from binary or hex back to int, but we need to specify the base:
We don't actually need the leading '0x' or '0':
So, the other day I should have just done:
When reading data from a file:
Although the file was opened in "binary" mode, the type actually read was <'str'>, and when the data are printed, it looks like a string. Nevertheless, the data do respond well to a function that operates on binary data and converts it to a hexadecimal string representation.
The result is rather different if we use the same function on the data as a whole:
In this case, the 8 bytes are converted to 16 hexadecimal characters, and to do the conversion to ints and chars we must read 2 char chunks of the hexadecimal.
Does that make sense?