473,388 Members | 932 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,388 software developers and data experts.

Need elegant way to cast four bytes into a long

I've got an array.array of unsigned char and would like to make a slice
of that array (e.g. a[0:4]) become one long like I would in "C" :

l = ((unsigned long *) (&a[0]))[0];

I have been getting what I want in this sort of manner :

l = 0L
l = a[0]
l += a[1] << 8
l += a[2] << 16
l += a[3] << 24

but I think that's too wordy. Is there a more intrinsic and elegant way
to do this?

---
wsh
Jul 18 '05 #1
9 2243

"William S. Huizinga" <wi**************@smiths-aerospace.com> wrote in
message news:3f********@news.si.com...
I've got an array.array of unsigned char and would like to make a slice of that array (e.g. a[0:4]) become one long like I would in "C" :

l = ((unsigned long *) (&a[0]))[0];

I have been getting what I want in this sort of manner :

l = 0L
l = a[0]
l += a[1] << 8
l += a[2] << 16
l += a[3] << 24

but I think that's too wordy. Is there a more intrinsic and elegant way to do this?


el = 0L+ a[0] + (a[1]<< 8) + (a[2]<<16) + (a[3] << 24)

is more compact and must be slightly faster (but parens are needed)

TJR

Jul 18 '05 #2
In article <3f********@news.si.com>, William S. Huizinga wrote:
I've got an array.array of unsigned char and would like to make a slice
of that array (e.g. a[0:4]) become one long like I would in "C" :

l = ((unsigned long *) (&a[0]))[0];
Bad C programming. Your program isn't portable.
I have been getting what I want in this sort of manner :

l = 0L
l = a[0]
l += a[1] << 8
l += a[2] << 16
l += a[3] << 24

but I think that's too wordy. Is there a more intrinsic and elegant way
to do this?


How about this:

l = a[0] + (a[1]<<8) + (a[2]<<16) + (a[3]<<24)

Or you can use struct:

l = struct.unpack("<I","".join([chr(b)for b in a]))[0]

I think that the former is more obvious.

--
Grant Edwards grante Yow! I always liked FLAG
at DAY!!
visi.com
Jul 18 '05 #3

wsh> I have been getting what I want in this sort of manner :

wsh> l = 0L
wsh> l = a[0]
wsh> l += a[1] << 8
wsh> l += a[2] << 16
wsh> l += a[3] << 24

wsh> but I think that's too wordy. Is there a more intrinsic and
wsh> elegant way to do this?

You mean like this:

l = long(a[0] + a[1] << 8 + a[2] << 16 + a[3] << 24)

You can use struct.unpack as well, though I'd be hard-pressed to get the
details correct. You'd be better off with "pydoc struct".

Skip
Jul 18 '05 #4
In article <3f*********************@newsreader.visi.com>, Grant Edwards wrote:
In article <3f********@news.si.com>, William S. Huizinga wrote:
I've got an array.array of unsigned char and would like to make a slice
of that array (e.g. a[0:4]) become one long like I would in "C" :

l = ((unsigned long *) (&a[0]))[0];


Bad C programming. Your program isn't portable.


Aside from the endian issue, it may even cause a bus fault or
completely bogus value on many architectures (ARM, SPARC,
etc.). It's actually quite difficult to duplicate that sort of
behavior in Python. ;)

--
Grant Edwards grante Yow! Remember, in 2039,
at MOUSSE & PASTA will
visi.com be available ONLY by
prescription!!
Jul 18 '05 #5
William S. Huizinga wrote:
I've got an array.array of unsigned char and would like to make a slice
of that array (e.g. a[0:4]) become one long like I would in "C" :

l = ((unsigned long *) (&a[0]))[0];


What about:

b = array.array('L')
b.fromstring(a[0:4].tostring())
l = b[0]

I think this should faithfully reproduce the endianness-related
unportability of that C fragment (cannot necessarily reproduce
crashes due to possible use of misaligned pointers, though:-).

Actually, I believe you do not really need the .tostring call
in modern Python -- just b.fromstring(a[0:4]) should be
equivalent (and faster). Better, if you need to transform
into longs _many_ adjacent segments of 4 bytes each, this
approach does generalize, and speed is good. Finally, you
can remedy endianness issue with the .byteswap method...

Alex

Jul 18 '05 #6
You mean like this:

l = long(a[0] + a[1] << 8 + a[2] << 16 + a[3] << 24)

John> Bzzzzzt. Oh the joys of operator precedence!

Yeah, I realized that after seeing a couple other responses. Should have
kept my mouth shut. I tend to think of << and >> as X2 and /2 operators and
thus mentally lump them together with * / and %. Fortunately, I don't do
much bit twiddling or I'd be in real trouble...

Skip

Jul 18 '05 #7
Skip Montanaro <sk**@pobox.com> wrote in message news:<ma**********************************@python. org>...
You mean like this:
>>
>> l = long(a[0] + a[1] << 8 + a[2] << 16 + a[3] << 24)
>>

John> Bzzzzzt. Oh the joys of operator precedence!

Yeah, I realized that after seeing a couple other responses. Should have
kept my mouth shut. I tend to think of << and >> as X2 and /2 operators and
thus mentally lump them together with * / and %. Fortunately, I don't do
much bit twiddling or I'd be in real trouble...


One correct way of writing the expression without parentheses is

a[0] | a[1] << 8 | a[2] << 16 | a[3] << 24
Jul 18 '05 #8
William S. Huizinga wrote:
I've got an array.array of unsigned char and would like to make a slice
of that array (e.g. a[0:4]) become one long like I would in "C" :

l = ((unsigned long *) (&a[0]))[0];

I have been getting what I want in this sort of manner :

l = 0L
l = a[0]
l += a[1] << 8
l += a[2] << 16
l += a[3] << 24

but I think that's too wordy. Is there a more intrinsic and elegant way
to do this?

def readBew(value):
"Reads string as big endian word, (asserts len(string) in [1,2,4])"
return unpack('>%s' % {1:'b', 2:'H', 4:'l'}[len(value)], value)[0]

def writeBew(value, length):
"""
Write int as big endian formatted string,
(asserts length in [1,2,4])
"""
return pack('>%s' % {1:'b', 2:'H', 4:'l'}[length], value)

Any of those usefull?

regards Max M

Jul 18 '05 #9
"William S. Huizinga" <wi**************@smiths-aerospace.com> wrote:
I've got an array.array of unsigned char and would like to make a slice
of that array (e.g. a[0:4]) become one long like I would in "C" :

l = ((unsigned long *) (&a[0]))[0];

I have been getting what I want in this sort of manner :

l = 0L
l = a[0]
l += a[1] << 8
l += a[2] << 16
l += a[3] << 24

but I think that's too wordy. Is there a more intrinsic and elegant way
to do this?


Just for completeness, it's also possible to go back to basic style
programming.

Anton

from string import hexdigits

def hexchr(i): return hexdigits[i/16]+hexdigits[i%16]
asc = dict([(chr(i), hexchr(i)) for i in range(256)])
def tolong(s): return long(''.join(map(asc.get,s[::-1])),16)

def test():
a = '\x01\x02\x03\x04'
print tolong(a)

if __name__=='__main__':
test()
Jul 18 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Graham Nicholls | last post by:
Hi, I'm trying to size a jpeg file. The file size is held in a short (2 byte integer) at a certain offset. Once I've found these two bytes (they're in MSB,LSB order), I need to convert them to...
9
by: rsine | last post by:
I have developed a program that sends a command through the serial port to our business system and then reads from the buffer looking for a number. Everything worked great on my WinXP system, but...
12
by: gcary | last post by:
I am having trouble figuring out how to declare a pointer to an array of structures and initializing the pointer with a value. I've looked at older posts in this group, and tried a solution that...
3
by: mrmattborja | last post by:
Hello, Here is a program I'm playing around with for fun in the process of learning C. The objective is to create a function filesize() and call it from within the main() section to retrieve the...
9
by: Joe | last post by:
I need to cast the correct way HMENU mymenu; int stuff; .... stuff=(int)(long)(HMENU)mymenu; ....
18
by: Felix Kater | last post by:
I haven't been thinking about it for years but recently I've stumbled on the fact that 'casting' is actually doing (at least) two different things: On the one hand 'casting' means: 'Change...
35
by: Bjoern Hoehrmann | last post by:
Hi, For a free software project, I had to write a routine that, given a Unicode scalar value U+0000 - U+10FFFF, returns an integer that holds the UTF-8 encoded form of it, for example, U+00F6...
4
by: Paul David Buchan | last post by:
Hello, I'm attempting to write a program to read in database files (.dbf). When I do it all as a single procedure in main, everything works. However, what I really want, is to pass the database...
33
by: Hahnemann | last post by:
Does anybody know the answer to the following? An unsigned short is 2 bytes long. Why is the following file created as 4 bytes instead of 2? file = fopen("data.bin", "wb"); if (file != NULL)...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.