473,785 Members | 2,291 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Need to convert an arbitrary byte-pair to an int.

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 an integer - now I know that in C
I'd just cast a pointer to the offset to a short, and that python doesn't
cast, so how can I extract the value from a stream of bytes. I've looked
at python.org/Doc/current (I'm using 2.3b1), but can't find anything
obvious.

Thanks

--
Graham Nicholls
Rock Computer Consultancy

Jul 18 '05 #1
3 11043
Graham Nicholls wrote:
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 an integer - now I know that in
C I'd just cast a pointer to the offset to a short, and that python
doesn't
cast, so how can I extract the value from a stream of bytes. I've looked
at python.org/Doc/current (I'm using 2.3b1), but can't find anything
obvious.


I see you've already been pointed to a 3rd party package that's useful for
handling images, but just in case you to need to solve in the future the
actual problem you pose in the subject, one elementary way might be:

thefile = open('whatever' , 'rb')
thefile.seek(th eoffset)
msb = thefile.read(1)
lsb = thefile.read(1)
theint = ord(lsb) + ord(msb) * 256

The struct module, which I see has also been pointed out to you already,
would let you compact the last three statements into one. So, in this
specific case, would the array module. Both struct and array are part
of the standard Python library and often come in handy for occasional
needs of low-level access, such as this.
Alex

Jul 18 '05 #2
<posted & mailed>

Alex Martelli wrote:
Graham Nicholls wrote:
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 an integer - now I know that
in C I'd just cast a pointer to the offset to a short, and that python
doesn't
cast, so how can I extract the value from a stream of bytes. I've looked
at python.org/Doc/current (I'm using 2.3b1), but can't find anything
obvious.
I see you've already been pointed to a 3rd party package that's useful for
handling images, but just in case you to need to solve in the future the
actual problem you pose in the subject, one elementary way might be:

thefile = open('whatever' , 'rb')
thefile.seek(th eoffset)
msb = thefile.read(1)
lsb = thefile.read(1)

theint = ord(lsb) + ord(msb) * 256 ^^^^^^^^^^^^^^^ ^^
This is what I was trying to do, only getting confused with abs, atoi and
various other invocations which either dont exist or don't do what I wanted
them to.

The struct module, which I see has also been pointed out to you already,
would let you compact the last three statements into one.
And IMO is rather more elegant.
So, in this
specific case, would the array module. Both struct and array are part
of the standard Python library and often come in handy for occasional
needs of low-level access, such as this.
Trouble is, you don't know what you don't know, and my python library
reference is at home, and I'm onsite.

Alex

Alex (and Richard),

Thanks for that. The struct module was just what I was after. (I cancelled
my reply which implied that the 3rd party module was the answer, when in
fact, I'd meant to say that using struct is _exactly_ what I want).

Jpeg files have a header, then a series of segments, each of which contains
within it the segment size, so using a struct (just like in c, really) is a
great way to read the segment type and size.

BTW, I posted a month or so back wondering about the merits of Python, which
I already much prefer to perl, but I've sort of simultaneously been
learning Ruby & Python. Not sure which I prefer, yet, but I think that a
reasonable knowledge of both, perhaps with in depth understanding of one of
them, would be useful. Python seems to have more modules, and I do like
lots of things about it, but Ruby _seems_ cleaner, somehow. Its an
interesting exercise, trying to learn both (whilst being quite busy).

Thanks again.
--
Graham Nicholls
Rock Computer Consultancy

Jul 18 '05 #3
Graham Nicholls wrote:
...
So, in this
specific case, would the array module. Both struct and array are part
of the standard Python library and often come in handy for occasional
needs of low-level access, such as this.
Trouble is, you don't know what you don't know, and my python library
reference is at home, and I'm onsite.


The python library reference is also online -- see for example
http://www.python.org/doc/current/lib/lib.html -- and if one happens
to prefer "Python in a Nutshell", why, THAT one is too (on O'Reilly's
"safari" service -- however, after some weeks' worth of free trial, if
you want to continue accessing "safari" you'd have to subscribe to it).

them, would be useful. Python seems to have more modules, and I do like
lots of things about it, but Ruby _seems_ cleaner, somehow. Its an


Interesting. I'm also trying to learn Ruby in my copious spare time
and don't really see that "clean-ness" (all of those 'end' terminators
of block, how are they "cleaner" than the lack thereof in Python? How
is it "cleaner" to have regular expressions deeply mixed in the
innards of the language rather than cleanly separated into their own
library modules? Etc, etc). I _do_ see that Ruby provides more scope
for tinkering, because it lets me play with the way operations on
built-in types work -- so if I want e.g. 2+2 to evaluate to 5, I can
(or more seriously, I can perform presumably-useful modifications to
other special methods of built-in types). But I think the same key
difference that makes Ruby better for tinkering -- the total fluidity
and dinamicity of just about everything, with no "fixed posts" for
the behavior of built-in types -- may make it less suitable for the
programming of large, multi-developers, indeed multi-team application
programs. Python is highly dynamic but draws the line at modifying
behavior of built-in types; Ruby draws no such line, and thus it is
even more dynamic. To me, on the basis of my understanding of both
languages so far, THAT is the one _crucial_ language difference (the
_libraries_ may differ more broadly, but that's secondary and even
easily remedied -- the languages' philosophy regarding such dynamic
possibilities, however, are far less likely to ever change).

Other more specific tradeoffs, such as Ruby's _mutable_ strings (which
I mostly dislike, but may sometimes help performance) or the very
different style of iterators in the two languages (in Ruby you pass a
code block into the iterator, while in Python you get values out of
the iterator one by one -- so, for example, stepping over more than
one iterator in a controlled way is far easier in Python, while
other tasks are easier in Ruby -- I think, overall, the power of
the very iterators in the two languages may be very similar, with a
tiny edge to Ruby, while the simplicity and syntax cleanliness of
coding is IMHO a substantial edge to Python) -- all of these can be
discussed point by point, of course.
Still, I agree that both languages are quite good. If Python did
not exist, I believe I would most probably be using Ruby, myself.
Alex

Jul 18 '05 #4

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

Similar topics

1
1663
by: Arnold Shore | last post by:
I need access to the bits of a Byte expression, and the logical functions operatge bit-wise on numeric vales - per the VBScript CHM. So how do I convert a Byte to its numeric value? Thanks, all. AS
19
4153
by: jeff | last post by:
how do you convert form byte to Int32 while retaining the binary value of the byte array
14
29520
by: Chris | last post by:
Hi, I try to print out truth-tables for an &&-operation using the following code, unfortunatly I get compiler errors : for ( byte i1=0; i1<=1; i1++) { for ( byte i2=0; i2<=1; i2++) { bool a = (bool)i1; // ERROR : convert type 'byte' to 'bool'
6
10230
by: Ricardo Quintanilla | last post by:
i have a code that sends data to a socket listening over as400 platform, the socket responds to me as a "byte array". then i need to convert the "byte array" into a string. the problem is that the data converted from the byte array into a string , is not what i expect. example: - the data returned from the socket is (byte array) "Usuario Sin Atribuciones Para Esta Función"
15
34607
by: Kueishiong Tu | last post by:
How do I convert a Byte array (unsigned char managed) to a char array(unmanaged) with wide character taken into account?
2
5457
by: moni | last post by:
hey, When I convert a byte into string values I do it like this: TextBox2.Text = System.Text.Encoding.ASCII.GetString(buffer, 0, 31); where buffer is my byte array where my data is stored. Can someone tell me what I would need to do , if I have to extract the unsigned short value from my byte array??
8
5911
by: Serge BRIC | last post by:
My application, written in .NET VB, tries to get a communication port handle from a TAPI object with this code: Dim vFileHandle As Byte() = appel.GetIDAsVariant("comm/datamodem") The vFileHandle is supposed to be a file handle (an IntPtr, I suppose). How can I convert this Byte() in this IntPtr ?
7
2484
by: =?Utf-8?B?RWl0YW4=?= | last post by:
What would be the "right" way to convert type 'byte' to 'string'? Thanks EitanB
4
5327
by: Pramod | last post by:
Hi. I have a C++ method which accepts - byte* - and I am calling this method from a C# application. I have created a byte to pass by ref. This is how I call the C++ method: Method(ref byteArray); However, this results in following error: Cannot convert 'ref byte' to 'ref byte'
3
11640
by: dpsairam | last post by:
Hi, How to convert a byte array to image....i mean i have to convert a Byte array into image format.....please hellp.........i need the java code... Thanking You.
0
9643
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9480
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10315
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10147
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10085
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9947
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8968
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5379
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.