[Tutor] int to bytes and the other way around

Kent Johnson kent37 at tds.net
Mon Jul 6 13:04:58 CEST 2009


On Mon, Jul 6, 2009 at 4:48 AM, Timo<timomlists at gmail.com> wrote:
> I have written a program that uses a C++ module as backend. Now I found out
> that I can use Python to call an underneath C lib. That's nice, so I don't
> need to Popen() the C++ module.
>
> I have a problem though with some info that is returned (always an integer).
> I'll try to explain a bit, this is what I found out so far.
> There are 4 options in the program. The first 3 options go up to 18 and the
> fourth to 7.
> If all options are set to 0, the returned int is 0.
> If the first option is set from 1 to 18, this is what I get returned.
> However, for option 2, I get 256, 512, 768, 1024, etc.
> For option 3 I get 65536, 131072, 196608, etc, etc.
> And for option 4: 16777216, 33554432, etc.
>
> Ok, that's nice so far. But if option 1 is set to 4 and option 2 is set to 8
> and option 3 is set to 10 (for example), I get this returned: 657412
>
> The C++ module counts the bytes. First byte = option1, second byte = option2
> etc.
>       u8 *options = (u8 *)&result[1];
>       option1 = options[0]
>       option2 = options[1]
>       option3 = options[2]
>       option4 = options[3]
>
> How will I approach this in Python?

Looks like you need the struct module.

Kent


More information about the Tutor mailing list