473,657 Members | 2,481 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Numeric type conversions

I'm new to Python and can't readily find the appropriate function for
the following situation:

I'm reading in a byte stream from a serial port (which I've got
working OK with pyserial) and which contains numeric data in a packed
binary format. Much of the data content occurs as integers encoded as
2 consecutive bytes, ie a 2-byte integer.

I'm guess that there should be a function available whereby I can say
something like:

My2ByteInt = ConvertToInt(By teStream[12:13])

to take a random example of the 2 bytes occurring at positions 12 and
13 in the byte stream.

Can anyone point me in the right direction towards a suitable function
please?

NB I don't know without further checking exactly how the bytes are
encoded, but I'm just transcribing some code across from a Windows
VB.Net program and these same bytes could be read straight into a
standard 2-byte signed short int, so I can be confident that it's a
fairly standard Windows-compatible encoding.
Jun 27 '08 #1
10 1306
John Dann wrote:
I'm new to Python and can't readily find the appropriate function for
the following situation:

I'm reading in a byte stream from a serial port (which I've got
working OK with pyserial) and which contains numeric data in a packed
binary format. Much of the data content occurs as integers encoded as
2 consecutive bytes, ie a 2-byte integer.

I'm guess that there should be a function available whereby I can say
something like:

My2ByteInt = ConvertToInt(By teStream[12:13])

to take a random example of the 2 bytes occurring at positions 12 and
13 in the byte stream.

Can anyone point me in the right direction towards a suitable function
please?
see the module struct in the standard-lib.

Diez
Jun 27 '08 #2
try struct.pack
Jun 27 '08 #3
On 2008-06-17, John Dann <ne**@prodata.c o.ukwrote:
I'm reading in a byte stream from a serial port (which I've got
working OK with pyserial) and which contains numeric data in a packed
binary format. Much of the data content occurs as integers encoded as
2 consecutive bytes, ie a 2-byte integer.
[snipperdesnip]
Can anyone point me in the right direction towards a suitable function
please?
The ctypes module should be helpful here

Sincerely,
Albert
Jun 27 '08 #4
John Dann wrote:
I'm new to Python and can't readily find the appropriate function for
the following situation:

I'm reading in a byte stream from a serial port (which I've got
working OK with pyserial) and which contains numeric data in a packed
binary format. Much of the data content occurs as integers encoded as
2 consecutive bytes, ie a 2-byte integer. [...]
Use the unpack() function from the struct module.

-- Gerhard

Jun 27 '08 #5
On Jun 17, 9:28 pm, John Dann <n...@prodata.c o.ukwrote:
I'm new to Python and can't readily find the appropriate function for
the following situation:

I'm reading in a byte stream from a serial port (which I've got
working OK with pyserial) and which contains numeric data in a packed
binary format. Much of the data content occurs as integers encoded as
2 consecutive bytes, ie a 2-byte integer.

I'm guess that there should be a function available whereby I can say
something like:

My2ByteInt = ConvertToInt(By teStream[12:13])

to take a random example of the 2 bytes occurring at positions 12 and
13 in the byte stream.

Can anyone point me in the right direction towards a suitable function
please?

NB I don't know without further checking exactly how the bytes are
encoded, but I'm just transcribing some code across from a Windows
VB.Net program and these same bytes could be read straight into a
standard 2-byte signed short int, so I can be confident that it's a
fairly standard Windows-compatible encoding.
You need the unpack function of the struct module. Supposing you have
a four-byte string containing two such short ints, first + 1 then -1
then this will work:
>>import struct
two_shorts = '\x01\x00\xff\x ff'
struct.unpack ('<hh', two_shorts)
(1, -1)
>>>
In the format string, '<' means little-endian (almost universal on PCs
running Windows), and 'h' means a signed 'half-word'. See the struct
manual section for more options.

You can write a function called convert_to_int (take a hint on naming
conventions) and use it a slice at a time, or you can use
struct.unpack to grab a whole record at once. Here's a real live
example of that:

(
f.height, option_flags, f.colour_index, f.weight,
f.escapement_ty pe, f.underline_typ e, f.family,
f.character_set ,
) = unpack('<HHHHHB BB', data[0:13])

HTH,
John
Jun 27 '08 #6
On Jun 17, 12:28 pm, John Dann <n...@prodata.c o.ukwrote:
I'm new to Python and can't readily find the appropriate function for
the following situation:

I'm reading in a byte stream from a serial port (which I've got
working OK with pyserial) and which contains numeric data in a packed
binary format. Much of the data content occurs as integers encoded as
2 consecutive bytes, ie a 2-byte integer.

I'm guess that there should be a function available whereby I can say
something like:

My2ByteInt = ConvertToInt(By teStream[12:13])

to take a random example of the 2 bytes occurring at positions 12 and
13 in the byte stream.
[snip]
Please note that in slicing the start position is included and the end
position is excluded, so that should be ByteStream[12:14].
Jun 27 '08 #7
On Tue, 17 Jun 2008 08:58:11 -0700 (PDT), MRAB
<go****@mrabarn ett.plus.comwro te:
>[snip]
Please note that in slicing the start position is included and the end
position is excluded, so that should be ByteStream[12:14].
Yes, I just tripped over that, in fact, hence the error in my original
post. I suppose there must be some logic in including the start
position but excluding the end position, though it does escape me for
now. I can understand making a range inclusive or exclusive but not a
mixture of the two. Suppose it's just something you have to get used
to with Python and, no doubt, much commented on in the past.

JGD
Jun 27 '08 #8
John Dann wrote:
On Tue, 17 Jun 2008 08:58:11 -0700 (PDT), MRAB
<go****@mrabarn ett.plus.comwro te:
>>[snip]
Please note that in slicing the start position is included and the end
position is excluded, so that should be ByteStream[12:14].

Yes, I just tripped over that, in fact, hence the error in my original
post. I suppose there must be some logic in including the start
position but excluding the end position, though it does escape me for
now. I can understand making a range inclusive or exclusive but not a
mixture of the two.
http://www.cs.utexas.edu/users/EWD/ewd08xx/EWD831.PDF

Peter
Jun 27 '08 #9
Lie
On Jun 18, 12:23*am, John Dann <n...@prodata.c o.ukwrote:
On Tue, 17 Jun 2008 08:58:11 -0700 (PDT), MRAB

<goo...@mrabarn ett.plus.comwro te:
[snip]
Please note that in slicing the start position is included and the end
position is excluded, so that should be ByteStream[12:14].

Yes, I just tripped over that, in fact, hence the error in my original
post. I suppose there must be some logic in including the start
position but excluding the end position, though it does escape me for
now. I can understand making a range inclusive or exclusive but not a
mixture of the two. Suppose it's just something you have to get used
to with Python and, no doubt, much commented on in the past.

JGD
There is actually a logic to that. It's explained in the help/tutorial
file, that you should think about the index as a cursor, the index
itself doesn't point to the item itself, but to the interval between
the item.

(read this on a monospace font, or it'll look screwed up)
0 1 2 3 4 5
+-------------------+
| A | B | C | D | E |
+-------------------+
-5 -4 -3 -2 -1 0

So to get BCD, you say [1:4]
Jun 27 '08 #10

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

Similar topics

8
2237
by: Rade | last post by:
Following a discussion on another thread here... I have tried to understand what is actually standardized in C++ regarding the representing of integers (signed and unsigned) and their conversions. The reference should be 3.9.1 (Fundamental types), and 4.7 (Integral conversions). It seems to me that the Standard doesn't specify: 1) The "value representation" of any of these types, except that (3.9.1/3) "... The range of nonnegative...
15
2281
by: buda | last post by:
Let me see if I got this :) 1. I know the rules for type conversions in arithmetic expressions 2. I know that an implicit type conversion is done at assignment, so float x = 1.23; int t = (int) x; is equivalent to int t = x; (could the latter produce a warning on some complier?) 3. I know that implicit conversions take place with function arguments, but am a bit shaky here. I suppose that passing a char to a function accepting
51
4507
by: jacob navia | last post by:
I would like to add at the beginning of the C tutorial I am writing a short blurb about what "types" are. I came up with the following text. Please can you comment? Did I miss something? Is there something wrong in there? -------------------------------------------------------------------- Types A type is a definition for a sequence of storage bits. It gives the meaning of the data stored in memory. If we say that the object a is an
2
12341
by: Sam Sungshik Kong | last post by:
Hello! I studied C# a little bit and am trying to compare it with VB.Net. There's 'Option Strict' in VB.Net. I thought that if I turn it on, it is as strict as C# when checking types. See the following codes. <vb.net>
3
21216
by: mra | last post by:
I want to cast an object that I have created from a typename to the corresponding type. Can anycone tell me how to do this? Example: //Here, Create the object of type "MyClass" object obj=Activator.CreateInstance(strAssemblyName, "MyClass"); //Now, I want to do something like ((MyClass)obj).Method //Can I do this?
4
7192
by: Dimitrios Charitatos | last post by:
Hello, I suspect that there is a quite straight forward answer to this, but I can't find it... I want to import an image and extract a matrix (or array) from it with elements showing the RGB value of each pixel. But I want to be able to do this with all types of image formats. It was suggested that a function such as 'B = numeric.from_image(A)' was used but I can't find it in any of the libraries. I was hoping you could help me on this....
11
2238
by: Pieter | last post by:
Hi, I'm having some troubles with my numeric-types in my VB.NET 2005 application, together with a SQL Server 2000. - I first used Single in my application, and Decimal in my database. But a Single with value 4.475 was converted to a Decimal with value 4.4749999999999996D. So after inserting and selecting it from the database I got another value than the original!
8
1827
by: pozz | last post by:
In my software, there are some variables that represents some settings. They usually are numerical variables: unsigned char (0..255), signed char (-127..128), unsigned int (0..65535), signed int (-32767..32768). I want to write a generic C function that changes the value of one parameter. For example, a function that takes a pointer to the variable and increments it by one. Of course, the function doesn't know the variable type (unsigned...
23
9770
by: neha_chhatre | last post by:
which is the best format specifier(data type) if i have to work with decimal number. also please tell me the syntax for truncating a decimal number please reply as soon as possible
0
8825
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
8732
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...
0
7327
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...
1
6164
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5632
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4152
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
4304
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2726
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1955
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.