number conversion

John Machin sjmachin at lexicon.net
Wed Apr 6 18:44:01 EDT 2005


On 6 Apr 2005 12:01:23 -0700, nicksjacobson at yahoo.com wrote:

>I'm writing a program to read in raw data from a WAV file, and write it
>to an IT file.  I got this to work in C by reading the data into an
>array of unsigned chars called "RawDataAry", then converted it to
>signed chars by doing the following:

It might help us help you if you explained why you think you need to
do this. An example or two might help: "I have these bytes in a WAV
file \xf0\x0b\xaa etc etc and I need to transform them into <whatever>
to write them to an IT file". Alternatively, "bytes in a WAV file
represent integers in range(A,B); bytes in an IT file represent
integers in range(C,D); I need to ...".

>
>signed char *CharAry = malloc(sizeof(signed char) * frames);
>for (i = 0; i < input_frames; i++)
>    CharAry[i] = (signed char)(((signed short)WavDataAry[i]) - 128);

WavDataAry or RawDataAry ??? Let's assume for the moment that they are
synonyms :-)

(1) raw is in an unsigned char, 0 <= raw <= 255
(2) casting that to a signed short gives you an I-don't-know-what
without some thought & flicking through K&R -- let's assume still 0 to
255
(3) subtracting 128 gives you -128 to +127
(4) which then gets cast as a signed char ....

Somehow I think your bit patterns have survived intact. 

May I ask a quick silly question: why don't you read it into an array
of signed chars in the first place??

Without further information, it appears that you want to travel from
New York City, NY to "The Big Apple", but you are diverting past Walla
Walla, WA.

>
>It worked.
>
>
>But when I tried to do this kind of conversion in Python, I got an
>OverflowError exception.
>
>First I read the data into an array of unsigned chars:
>
>fmt = str(chunklen) + 'B'
>fmtsize = struct.calcsize(fmt)
>rawdata = struct.unpack(fmt, s[:fmtsize])
>rawdata = list(rawdata)
>
>Then I tried to convert it:
>
>charary = array.array('b')
>charary.fromlist(rawdata)
>
>This last line threw the OverflowError exception, "OverflowError:
>signed char is greater than maximum."

That would be because you omitted one step in emulating your C antics:
subtracting 128.

>
>Is there a way to do this?? 

We're still not sure what "this" is.

> Thanks a lot in advance!!
>
>--Nick




More information about the Python-list mailing list