By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,898 Members | 1,162 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,898 IT Pros & Developers. It's quick & easy.

4 byte integer

P: n/a
Greetings everyone. I'm a relative newcomer to python and I have a technical
problem.

I want to split a 32 bit / 4 byte unsigned integer into 4 separate byte
variables according to the following logic: -

bit numbers 0..7 byte 1
bit numbers 8..15 byte 2
bit numbers 16..23 byte 3
bit numbers 24..31 byte 4

Each of these byte variables to contain integer data from 0 to 255 (or 0 to
FF in hex mode)

I had thought that struct.unpack with an input message format of 'I' would
be the way to do it, but its reporting an error that it doesn't want to
accept an integer.

Please can anyone advise?

May 11 '07 #1
Share this Question
Share on Google+
3 Replies


P: n/a

On May 11, 2007, at 4:25 AM, Paul D Ainsworth wrote:
Greetings everyone. I'm a relative newcomer to python and I have a
technical
problem.

I want to split a 32 bit / 4 byte unsigned integer into 4 separate
byte
variables according to the following logic: -

bit numbers 0..7 byte 1
bit numbers 8..15 byte 2
bit numbers 16..23 byte 3
bit numbers 24..31 byte 4

Each of these byte variables to contain integer data from 0 to 255
(or 0 to
FF in hex mode)

I had thought that struct.unpack with an input message format of
'I' would
be the way to do it, but its reporting an error that it doesn't
want to
accept an integer.

Please can anyone advise?
Have a look at http://aspn.activestate.com/ASPN/Cookbook/Python/
Recipe/113799
May 11 '07 #2

P: n/a
>
Have a look at http://aspn.activestate.com/ASPN/Cookbook/Python/
Recipe/113799
Brilliant - thank you :)
May 11 '07 #3

P: n/a
Paul D Ainsworth <pa*********@nospam.supanet.comwrote:
Greetings everyone. I'm a relative newcomer to python and I have a technical
problem.
I want to split a 32 bit / 4 byte unsigned integer into 4 separate byte
variables according to the following logic: -
bit numbers 0..7 byte 1
bit numbers 8..15 byte 2
bit numbers 16..23 byte 3
bit numbers 24..31 byte 4
Each of these byte variables to contain integer data from 0 to 255 (or 0 to
FF in hex mode)
I had thought that struct.unpack with an input message format of 'I' would
be the way to do it, but its reporting an error that it doesn't want to
accept an integer.
Please can anyone advise?
Would something like this work?

def word2bytes(n):
"""Given an positive integer n, return a tuple of 4 bytes from
n's least significant 32-bits
"""
r = []
n &= 0xFFFFFFFFL
for i in range(4):
r.append(n & 0xFF)
n >>= 8
r.reverse()
return tuple(r)



--
Jim Dennis,
Starshine: Signed, Sealed, Delivered

Jun 10 '07 #4

This discussion thread is closed

Replies have been disabled for this discussion.