Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting char from string its hex value

I currently get a string as a parameters in my method, i would like to extract the char in the I index and get it's hex value. Currently i'm doing :

temp = string[i]
binascii.hexlify(temp);

but i get an error :

TypeError: 'str' does not support the buffer interface

Any ideas please ?

like image 392
SagiLow Avatar asked Sep 26 '26 02:09

SagiLow


1 Answers

You need to encode the string to bytes:

binascii.hexlify(temp.encode('ascii'));

You'll need to pick a suitable encoding, one that can represent your text properly; I am presuming that your unicode characters fall in the 0-127 range here.

If you encode to a different encoding, the result will be a hex representation of that encoding. UTF-8 will use between 1 and 6 bytes per character for example.

Alternatively, you could use the ord() function and format the result to hex:

format(ord(temp), 'x')

and it'll work with any unicode character. It'll use the Unicode code point for the hex representation, so between 1 and 4 bytes (the latter for \Uabcdefgh wide characters). Depending on your maximum character width, you may want to pad the bytes to prevent ambiguous code points; say you need to encode up to codepoint \uffff then you'll need to use 2 bytes for every codepoint, or 4 hex characters:

format(ord(temp), '04x')
like image 161
Martijn Pieters Avatar answered Sep 27 '26 16:09

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!