473,503 Members | 13,381 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(ByteStream[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 1291
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(ByteStream[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.co.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.co.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(ByteStream[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\xff'
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_type, f.underline_type, f.family,
f.character_set,
) = unpack('<HHHHHBBB', data[0:13])

HTH,
John
Jun 27 '08 #6
On Jun 17, 12:28 pm, John Dann <n...@prodata.co.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(ByteStream[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****@mrabarnett.plus.comwrote:
>[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****@mrabarnett.plus.comwrote:
>>[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.co.ukwrote:
On Tue, 17 Jun 2008 08:58:11 -0700 (PDT), MRAB

<goo...@mrabarnett.plus.comwrote:
[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
John Dann <ne**@prodata.co.ukwrites:
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.
Half-open ranges are not specific to Python: for example, they're used
in Java (String.substring), Lisp (start and stop arguments to sequence
functions), and C++ (STL algorithms accept begin and end iterators
that generalize from pointers to the beginning and one-past-the-end of
an array).

Ranges so expressed have several nice properties. The size of the
range is expressed simply as b-a, you don't need to remember to add 1.
Empty range is easily expressed as [a, a>, rather than the much less
intuitive [a, a-1] for all-inclusive ranges. Consecutive ranges are
easily concatenated without missing or duplicating an element, so
[a, b+ [b, cis exactly equivalent to [a, c>.
Jun 27 '08 #11

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

Similar topics

8
2221
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....
15
2269
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)...
51
4452
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...
2
12335
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...
3
21199
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...
4
7186
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...
11
2218
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...
8
1810
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...
23
9746
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
7213
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
7366
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...
1
7017
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...
1
5026
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...
0
4698
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...
0
3187
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...
0
1526
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 ...
1
754
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
406
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

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.