473,698 Members | 2,337 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Binary representation of floating point numbers

Hi,

I'm using python to run some lab equipment using PyVisa. When I read a
list of values from the equipment, one of the fields is 32 bits of
flags, but the value is returned as a floating point number, either in
ASCII format, or pure binary. In either case, since I'm using PyVisa,
it converts the number to a single precision floating point, and that's
what I have to work with.

The question is how do I recover the bits out of this floating point
value so I can read the flags represented here?

Also, it's little (or big?) endian. Whatever... how do I manipulate
the endianness?

thanks
Michael

Dec 6 '05 #1
10 4180
On 2005-12-06, 63*******@sneak email.com <63*******@snea kemail.com> wrote:
I'm using python to run some lab equipment using PyVisa. When I read a
list of values from the equipment, one of the fields is 32 bits of
flags, but the value is returned as a floating point number, either in
ASCII format, or pure binary.
Wha? That doesn't make any sense. If it's 32 bits of flags,
then it's not a floating point number "in pure binary".

I suppose you could pretend the 32 bit chunk is a float and
print the resulting value, but that's just insane. And it
won't work. For some bit patterns, there's no way to go from
ASCII back to that same bit pattern. IOW, there is not a 1:1
mapping between bit patterns and the string representation, so
if that's what you've got, you're screwed.
In either case, since I'm using PyVisa, it converts the number
to a single precision floating point, and that's what I have
to work with.
It sounds like PyVisa is broken if it's treating someting as a
float when it isn't.
The question is how do I recover the bits out of this floating
point value so I can read the flags represented here?
Use the struct module.
Also, it's little (or big?) endian. Whatever... how do I
manipulate the endianness?


Again, the struct module.

--
Grant Edwards grante Yow! ... I have read the
at INSTRUCTIONS...
visi.com
Dec 6 '05 #2
63*******@sneak email.com writes:
Hi,
I'm using python to run some lab equipment using PyVisa. When I read a
list of values from the equipment, one of the fields is 32 bits of
flags, but the value is returned as a floating point number, either in
ASCII format, or pure binary.
Value returned by *what*? Your equipment doesn't return floating
point numbers, it returns bytes. Those can be interpreted in any
number of ways. What you have to do is get those bytes into something
that lets you read the bits out of it. How you do that depends on how
you're getting the bytes.
In either case, since I'm using PyVisa,
it converts the number to a single precision floating point, and that's
what I have to work with.
If the conversion is anything but trivial, there's a fair chance the
information you're interested is destroyed by it.
The question is how do I recover the bits out of this floating point
value so I can read the flags represented here?
I'm not sure this is doable in Python. I'm not sure I *want* it to be
doable in Python. In C, you use a cast.
Also, it's little (or big?) endian. Whatever... how do I manipulate
the endianness?


On most processors, you don't. If you can, doing so will cause the OS
to come to a screeching halt on most of them. I don't know if anyone
still building boxes that treats the underlying platform as context to
the degree you're asking for here.

<mike
--
Mike Meyer <mw*@mired.or g> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
Dec 6 '05 #3
Hi,

okay, let me be more concise. The lab equipment has two formatting
modes, ascii, and float.

In ascii mode, it returns strings that represent the numeric value, so
e.g. 3.14 is returned as '3.14'. PyVisa, when set to read ascii mode,
will convert these strings to float with "visa.read_valu es()". (easy
enough to do myself too with visa.read(), split(), and eval()).

In float mode, the instrument returns a sequence of bits that are
exactly the ieee754 number in the case of floats, or just the flags in
the case of flags. PyVisa, when set to float mode, will convert
everything to float, because it is unaware apriori that one of the
fields returned is actually intended to be used as binary flags.

Secondarily, I had to set the instrument to return the bits in small
endian for it to read properly (I could aternately set PyVisa to swap
endianness for me). I may need to manipulate this.

Actually now that I read the very confusing manual, it looks like maybe
the flags is returned as a decimal number, but it's not clear how this
is returned in either ascii or float mode. In any case, I think I will
need to manipulate "native" numbers into binary representation. Looks
like I should figure out the struct module...

Michael

Dec 6 '05 #4
Ok, I figured it out...

The only way to get the flags is as a float, either through an ascii
string or a true float. The value of the float, however, is
representable as 24 bits of normal binary.

So for example, the value returned is +4.608400E+04
which is really an int, 46084, which is more easily convertible to
binary.

So the question becomes how to convert an int to binary, which I found
here
http://groups.google.com/group/comp....bc9b0d8174b038

So problem solved (just need to implement it).

Michael

Dec 6 '05 #5
On 2005-12-06, 63*******@sneak email.com <63*******@snea kemail.com> wrote:
The only way to get the flags is as a float, either through an
ascii string or a true float.
That's perverse.

Really.

Somebody needs to be slapped.
The value of the float, however, is representable as 24 bits
of normal binary.
OK, that should preserve a 1:1 mapping between strings/floats
and flag bit patterns. It's still sick, though.
So for example, the value returned is +4.608400E+04 which is
really an int, 46084, which is more easily convertible to
binary.
You really don't need to convert it to "binary". Just convert
it to an integer object.
So the question becomes how to convert an int to binary, which
I found here

http://groups.google.com/group/comp....bc9b0d8174b038


I doubt you actually want to do that. Just leave it as an
integer, and test for the bits you care about:

def bit(n):
return 1<<n

flags = int(half_assed_ float_represent ing_the_flag_va lues)

if flags & bit(0):
print "underrange "
if flags & bit(1):
print "overrange"
if flags & bit(19):
print "bit 19 is set but nobody can hear me scream"
if flags & bit(23):
callThePolice()

or whatever.

--
Grant Edwards grante Yow! I feel better about
at world problems now!
visi.com
Dec 6 '05 #6
63*******@sneak email.com writes:
In float mode, the instrument returns a sequence of bits that are
exactly the ieee754 number in the case of floats, or just the flags in
the case of flags. PyVisa, when set to float mode, will convert
everything to float, because it is unaware apriori that one of the
fields returned is actually intended to be used as binary flags.
You need to get PyVisa to return strings of bytes to you.
Actually now that I read the very confusing manual, it looks like maybe
the flags is returned as a decimal number, but it's not clear how this
is returned in either ascii or float mode. In any case, I think I will
need to manipulate "native" numbers into binary representation. Looks
like I should figure out the struct module...


Struct is the right tool for the job. But it manipulates strings of
bytes. If worst comes to worst, you could take the float returned by
PyVisa, use struct.pack to turn it into a string of bytes, then
struct.unpack to treat it as an integer on which you can do bit
manipulations. That works so long as everyone agrees about all the
details of the floating point representation. But you'd be better off
reading bytes and using struct.unpack to get an integer from them.

<mike
--
Mike Meyer <mw*@mired.or g> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
Dec 6 '05 #7
Actually that's probably the easiest way. I may want to use shorter
variable names :)

thanks
michael

Dec 7 '05 #8
On Tue, 06 Dec 2005 22:51:03 -0000, Grant Edwards <gr****@visi.co m> wrote:
On 2005-12-06, 63*******@sneak email.com <63*******@snea kemail.com> wrote:
The only way to get the flags is as a float, either through an
ascii string or a true float.


That's perverse.

Really.

Somebody needs to be slapped.
The value of the float, however, is representable as 24 bits
of normal binary.


OK, that should preserve a 1:1 mapping between strings/floats
and flag bit patterns. It's still sick, though.
So for example, the value returned is +4.608400E+04 which is
really an int, 46084, which is more easily convertible to
binary.


You really don't need to convert it to "binary". Just convert
it to an integer object.
So the question becomes how to convert an int to binary, which
I found here

http://groups.google.com/group/comp....bc9b0d8174b038


I doubt you actually want to do that. Just leave it as an
integer, and test for the bits you care about:

def bit(n):
return 1<<n

flags = int(half_assed_ float_represent ing_the_flag_va lues)

if flags & bit(0):
print "underrange "
if flags & bit(1):
print "overrange"
if flags & bit(19):
print "bit 19 is set but nobody can hear me scream"
if flags & bit(23):
callThePolice()

or whatever.

You could also make a "whatever" like
class Bitview(long): ... def __new__(cls, v, width=32):
... inst = long.__new__(cl s, v)
... inst.width = width
... return inst
... def __getitem__(sel f, i):
... if isinstance(i, slice): return list(self)[i]
... if i>=self.width or i+self.width<0:
... raise IndexError, '%r has only %r bits' %(long(self), self.width)
... if i<0: i = i + self.width
... bit = 1<<i
... return self&bit and 1 or 0
... def __repr__(self): return "Bitview(int('% s', 2))"% str(self)
... def __str__(self): return ''.join(map(str , self))[::-1]
... bv11 = Bitview(11, 8)
bv11 Bitview(int('00 001011', 2)) bv11[8] Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 9, in __getitem__
IndexError: 11L has only 8 bits list(bv11) [1, 1, 0, 1, 0, 0, 0, 0] bv11[::-1] [0, 0, 0, 0, 1, 0, 1, 1] bv11[-1] 0 bv11[-5] 1 bv11[-6] 0 bv11[:4] [1, 1, 0, 1] str(bv11) '00001011' repr(bv11) "Bitview(int('0 0001011', 2))" eval(repr(bv11) ) == bv11 True import sys
Bitview(sys.max int)

Bitview(int('01 111111111111111 111111111111111 ', 2))

Add niceties to taste ;-)
Regards,
Bengt Richter
Dec 7 '05 #9
That looks pretty cool. I'll try it out.

thanks
Michael

Dec 7 '05 #10

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

Similar topics

27
4996
by: Eric | last post by:
Assume that disk space is not an issue (the files will be small < 5k in general for the purpose of storing preferences) Assume that transportation to another OS may never occur. Are there any solid reasons to prefer text files over binary files files?
2
3634
by: geskerrett | last post by:
In the '80's, Microsoft had a proprietary binary structure to handle floating point numbers, In a previous thread, Bengt Richter posted some example code in how to convert these to python floats; http://groups.google.com/group/comp.lang.python/browse_thread/thread/42150ccc20a1d8d5/4aadc71be8aeddbe#4aadc71be8aeddbe I copied this code and modified it slightly, however, you will notice that for one of the examples, the conversion isn't...
3
9615
by: Tanuki | last post by:
Hi All: I encounter a programming problem recently. I need to read a binary file. I need to translate the binary data into useful information. I have the format at hand, like 1st byte = ID, next 4 byte (int) = serial number etc. The first problem is Big Endian/ Little Endian problem. I can decipher if the format is big or little endian. But got confuse as to how to decipher the data.
8
9523
by: Yeow | last post by:
hello, i was trying to use the fread function on SunOS and ran into some trouble. i made a simple test as follows: i'm trying to read in a binary file (generated from a fortran code) that contains the following three floating-point numbers: 1.0 2.0 3.0
25
3638
by: Gaurav Verma | last post by:
Hi, I want to convert a floating point number (or a decimal number say 123.456) into binary notation using a C program. Can somebody help me out with it? Thanks Gaurav -- comp.lang.c.moderated - moderation address: clcm@plethora.net
64
3914
by: yossi.kreinin | last post by:
Hi! There is a system where 0x0 is a valid address, but 0xffffffff isn't. How can null pointers be treated by a compiler (besides the typical "solution" of still using 0x0 for "null")? - AFAIK C allows "null pointers" to be represented differently then "all bits 0". Is this correct? - AFAIK I can't `#define NULL 0x10000' since `void* p=0;' should work just like `void* p=NULL'. Is this correct?
7
8379
by: Gary Baydo | last post by:
In an effort to write a simple rounding function, I wrote the following code out of curiosity. My question is, can I rely on the output to 'make sense'? As an added 'exercise' I tried to write the code in a portable manner, not just for my box that uses 8-bit bytes and 4-byte floats. Comments and critiques are welcome. Thanks.
5
1652
by: gdarian216 | last post by:
im doing conversions with two's complement binary numbers and i have some questions. how can I convert -2047 into a base 2 complement number? I know how to read the binary but there has to be a way to convert it I just don't know how. I also was trying to figure out how to convert MIPS binary representation for the floating-point number 0.1. also i solved these and wanted to make sure I was understanding the concepts. if this is the...
17
264
by: Bill Cunningham | last post by:
I was wondering if someone could look this file over for me. It compiles correctly and prints the number 2 so I know fscanf is working. I am reading a text file and converting the text data obtained into a binary file. Now here's my specific question. I have two doubles separated by a tab in the text data. Are tabs preserved if you do what I have? My text file looks like this ..26 0.00 and that's all and there's a tab there. Here's...
0
8608
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
9161
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
9029
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
8897
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,...
1
6522
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
5860
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
4619
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3050
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
3
2006
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 can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.