开发者

chr(n) failed when n exceeds 256

开发者 https://www.devze.com 2023-03-31 09:01 出处:网络
I am using chr and int to convert a binary representation string to real binary value. What I did is n=int(\'0101011\',2)

I am using chr and int to convert a binary representation string to real binary value.

What I did is

   n=int('0101011',2)
   binary=chr(n)

Then binary is the real binary value of the representation string.

But what if the string I gave to int is larger than 256 in decimal?

Any solution开发者_StackOverflow社区?

PS: The reason I use chr is I want to convert n to a string so that I can write it to a file, using f.write().

And this question is originated from this question


chr() is defined as operating on ASCII characters, which must be less than 256 in value. If you are expecting Unicode characters, you can use unichr() instead.


You can use different format characters in the format string given to the pack() method in the struct module to easily get the corresponding binary representation string of signed or unsigned integers from 1 to 8 bytes in length.

>>> from struct import pack
>>> pack('B', 255)
'\xff'
>>> pack('H', 257)
'\x01\x01'
>>> pack('Q', 9223372036854775807)
'\xff\xff\xff\xff\xff\xff\xff\x7f'

The value returned can be written to a file using f.write() if desired. When reading or writing binary data to a file, you should append 'b' to the mode argument value when you open() the file.


If I understand your question you want to convert a binary string to an integer value. That is what you are doing in the first line of code. The second line just converts an integer value to the character represented by that value in the ASCII table. So, for example if the string is 01100001 that will be converted to an int value of 97 in the first step. Tue second step will then convert 97 to the ASCII character 'a'. If you then try to use this variable as a number it will be converted back to the ing value of 97. So, if I understand your question you actually have your desired number after step 1.


When trying to convert unicode values you can run into a multitude of problems. So using unichr is not always possible either, for example:

>>> n = int('0001f600', 16)
>>> unichr(n)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: unichr() arg not in range(0x10000) (narrow Python build)

Notice the narrow Python build message in the error, this means Python was built without wide unicode characters support, but even narrow Python can get around this limitation (without having to be recompiled with the --enable-unicode=ucs4 flag):

>>> n = int('0001f600', 16)
>>> s = '\\U{:0>8X}'.format(n)
>>> s
'\\U0001F600'
>>> binary = s.decode('unicode-escape')
>>> print(binary)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号