Reputation: 4521
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)
Upvotes: 2
Views: 9873
Reputation: 26757
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.
Upvotes: 2
Reputation: 102922
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.
Upvotes: 1
Reputation:
It does not work, because x
is not between 0 and 256.
chr
must be given an int
between 0 and 256.
Upvotes: 1