2

Let's say I have integer x (-128 <= x <= 127). How to convert x to signed char?

I did like this. But I couldn't.

>>> x = -1
>>> chr(x)
ValueError: chr() arg not in range(256)
Kei Minagawa
  • 4,395
  • 3
  • 25
  • 43

3 Answers3

2

Within Python, there aren't really any borders between signed, unsigned, char, int, long, etc. However, if your aim is to serialize data to use with a C module, function, or whatever, you can use the struct module to pack and unpack data. b, for example, packs data as a signed char type.

>>> import struct
>>> struct.pack('bbb', 1, -2, 4)
b'\x01\xfe\x04'

If you're directly talking to a C function, use ctypes types as Ashwin suggests; when you pass them Python translates them as appropriate and piles them on the stack.

Nick T
  • 25,754
  • 12
  • 83
  • 121
1

It does not work, because x is not between 0 and 256.

chr must be given an int between 0 and 256.

1

In Python 3, chr() does not convert an int into a signed char (which Python doesn't have anyway). chr() returns a Unicode string having the ordinal value of the inputted int.

>>> chr(77)
'M'
>>> chr(690)
'ʲ'

The input can be a number in any supported base, not just decimal:

>>> chr(0xBAFF)
'뫿'

Note: In Python 2, the int must be between 0 and 255, and will output a standard (non-Unicode) string. unichr() in Py2 behaves as above.

MattDMo
  • 100,794
  • 21
  • 241
  • 231
  • Somewhat strange there isn't a `from six.moves import chr` if those two are one and the same. – Nick T Oct 06 '14 at 03:41
  • @Ashwini correct. I think in Py3 most of the time :) I updated my answer to address its functions in **both** versions – MattDMo Oct 06 '14 at 03:41