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.mod erated - moderation address: cl**@plethora.n et
Nov 14 '05
25 3653
On 16 Sep 2004 14:25:56 -0700, ol*****@inspire .net.nz (Old Wolf) wrote
in comp.lang.c: Brian Gough <bj*@network-theory.co.uk> wrote: ve**********@gm ail.com (Gaurav Verma) writes:
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?
If you want the underlying IEEE representation of a floating point number you can use a union to access the individual bytes.
e.g. union { double d; struct { unsigned char byte[8]; } ieee ; } u;
This is undefined behaviour; to be portable you should go: unsigned char *ptr = (unsigned char *)&d; and then access the first (sizeof d) bytes of ptr.
Also note that the size of double is not required to be 8, and it is not required to use IEEE format (although usually it is).
The union method is neither more nor less portable than the type
punning through the pointer. Any object in C may be accessed as an
array of unsigned character types, this being specifically defined as
its "object representation" .
--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.l earn.c-c++ http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
In <41************ **@yahoo.com> CBFalconer <cb********@yah oo.com> writes: Dan Pop wrote: CBFalconer <cb********@yah oo.com> writes: Brian Gough wrote: ... snip ... If you want the underlying IEEE representation of a floating point number you can use a union to access the individual bytes.
e.g. union {double d; struct {unsigned char byte[8];} ieee ;} u;
No you can't, at least not portably.
Care to elaborate on the portability problems of:
union { double d; unsigned char bytes[sizeof(double)]; } u;
As I understand it accessing a union member as other than the type that was stored in it is either implementation or undefined.
As usual, you have difficulties engaging your brain...
In this particular case, the result is implementation-defined for
*exactly* the same reason it is implementation-defined in your suggested
method: the representation of floating point values itself is
implementation-defined.
Aliasing any object by an array of unsigned char is blessed by the
standard, no matter how the aliasing is achieved. See 6.5p7 and its
footnote.
Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Currently looking for a job in the European Union
Dan Pop wrote: In <41************ **@yahoo.com> CBFalconer <cb********@yah oo.com> writes:
Dan Pop wrote:
CBFalconer <cb********@yah oo.com> writes:
Brian Gough wrote:
... snip ...
>If you want the underlying IEEE representation of a floating >point number you can use a union to access the individual bytes. > >e.g. union {double d; struct {unsigned char byte[8];} ieee ;} u;
No you can't, at least not portably.
Care to elaborate on the portability problems of:
union { double d; unsigned char bytes[sizeof(double)]; } u;
As I understand it accessing a union member as other than the type that was stored in it is either implementation or undefined.
As usual, you have difficulties engaging your brain...
In this particular case, the result is implementation-defined for *exactly* the same reason it is implementation-defined in your suggested method: the representation of floating point values itself is implementation-defined.
Aliasing any object by an array of unsigned char is blessed by the standard, no matter how the aliasing is achieved. See 6.5p7 and its footnote.
Given float and unsigned int are both 32 bits wide (on my system)..
union {
float f;
unsigned u;
} flt;
flt.f = 1.0;
Now, examining flt.u we find it's 32 bits look like..
00111111 10000000 00000000 00000000
Still as flt.u we split it up to its float components.
Exp = 127 (1)
00000001
Man = .10000000 00000000 00000000
Having assigned to flt.f, does examining flt.u cause problems?
Clearly we are allowed to examine flt as..
unsigned char *ft = (unsigned char *)&flt;
...and examine ft[0] through ft[3] without problem.
--
Joe Wright mailto:jo****** **@comcast.net
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
In article <news:5a******* *************@c omcast.com>
Joe Wright <jo********@com cast.net> wrote: Given float and unsigned int are both 32 bits wide (on my system)..
union { float f; unsigned u; } flt;
flt.f = 1.0;
[snippage]
Having assigned to flt.f, does examining flt.u cause problems?
Possibly. That it must work, the C Standards sayeth not; and in
fact, at least one implementation (gcc, on SPARC) sometimes seems
to leave the floating point part in a floating point register, and
the integer part in an integer register, and never the twain do
meet. The bits found in flt.u thus have no correspondence to those
underlying flt.f.
Exposing the problem is tricky, as the optimization changes the
machine code if the source code is even sneezed-upon.
Clearly we are allowed to examine flt as..
unsigned char *ft = (unsigned char *)&flt;
..and examine ft[0] through ft[3] without problem.
Yes -- and this did work on that same gcc.
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
I don't know any special function for this in C, but it is very easy to do
if you know method of convertion... If you need if, I can describe...
--
LM
--
comp.lang.c.mod erated - moderation address: cl**@plethora.n et
Gaurav Verma wrote: 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?
#include <stdio.h>
#include <limits.h>
#define E_TYPE float
#define STRING " %s = %f\n"
#define VALUE 123.456f
typedef E_TYPE e_type;
void bitstr(char *, void const *, size_t);
int main(void)
{
e_type e;
char ebits[CHAR_BIT * sizeof e + 1], *s;
s = STRING;
e = VALUE;
bitstr(ebits, &e, sizeof e);
printf(s, ebits, e);
return 0;
}
void bitstr(char *str, const void *obj, size_t n)
{
unsigned mask;
const unsigned char *byte = obj;
while (n--) {
mask = ((unsigned char)-1 >> 1) + 1;
do {
*str++ = (char)(mask & byte[n] ? '1' : '0');
mask >>= 1;
} while (mask != 0);
}
*str = '\0';
}
--
pete
--
comp.lang.c.mod erated - moderation address: cl**@plethora.n et ve**********@gm ail.com (Gaurav Verma) writes: 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?
If I understand you right, that you want print out a binary notation of
a floating point number, here is an algorithm that will do this:
1) Divide the number into pre and post comma part
2) Convert each part into a string
3) Print out the two converted parts delimited by a '.'
Here is (one) way to convert a number into a binary representation:
----------8<-------------------snapp------------------------>8----------
char* getBinRep(unsig ned char number)
{
char* help;
unsigned char comp_mask = 0x1 << ((sizeof(char) * 8) -1);
char* bin_rep = malloc(sizeof(c har) * sizeof(char) * 8 + 1);
if(!bin_rep)
standartErrorHa ndler(OUT_OF_ME MORY);
help = bin_rep;
while(comp_mask )
{
*help++ = (number & comp_mask) ? '1' : '0';
comp_mask >>= 1;
}
*help = '\0';
return(bin_rep) ;
}
----------8<-------------------snipp------------------------>8----------
HTH && kind regards,
Nicolas
--
| Nicolas Pavlidis | Elvis Presly: |\ |__ |
| Student of SE & KM | "Into the goto" | \|__| |
| pa****@sbox.tug raz.at | ICQ #320057056 | |
|-------------------University of Technology, Graz----------------|
--
comp.lang.c.mod erated - moderation address: cl**@plethora.n et ve**********@gm ail.com (Gaurav Verma) wrote: 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?
What, _exactly_, have you got; what, exactly do you want? Have you got a
float in memory, or a string containing "123.456"? Do you want a float
in memory (since all C objects are stored binarily), or do you want a
string containing "1010.1010" ?
If you want to go from string to object, use strtod().
If you want to go from object to binary representation in memory, do
nothing; you've already got it.
If you want to go from object to string, that's harder; there is no
built-in printf() specifier for binary as there is for decimal and hex,
so you'll have to roll your own. Keep dividing by two and adding ones or
zeroes depending on the modulus.
If you want to go from decimal representation string to binary
representation string, it's probably easiest to use strtod() first and
then apply the previous solution.
Richard
--
comp.lang.c.mod erated - moderation address: cl**@plethora.n et
"Gaurav Verma" <ve**********@g mail.com> wrote 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?
Take the second logarithm of the number passed in. This tells you the place
value of the first binary digit.
Set that digit to a 1, then subtract from the passed number. Check for
equality or greater with the power of 2 1 less than the greatest digit. This
tells you if the next binary digit is 1 or zero. If it is 1, subtract.
Continue until the value goes to 0 or infinitesimal (the smallest positive
number representable in your floating point format).
--
comp.lang.c.mod erated - moderation address: cl**@plethora.n et ve**********@gm ail.com (Gaurav Verma) writes: 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?
Your question is ambiguous. What kind of binary representation are
you looking for? Do you want to see the representation of the
floating point number (sign, exponent, mantissa)? Or are you looking
for a binary representation of the mathematical value, something like
"1111011.011110 110100" for 123.456?
--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
--
comp.lang.c.mod erated - moderation address: cl**@plethora.n et This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Roger Leigh |
last post by:
Hello,
I'm writing a fixed-precision floating point class, based on the ideas
in the example fixed_pt class in the "Practical C++ Programming" book
by Steve Oualline (O' Reilly). This uses a long int to store the
value, and the precision (number of decimal points) is variable (it's
a templated class):
template <size_t _decimal_places = 4>
class FixedFloat {
|
by: Ketan Parikh |
last post by:
Hey everybody,
I am new to this group. I am from India.
Consider the following code.
main()
{
float k=0.7;
if (k < 0.7)
|
by: cody |
last post by:
no this is no trollposting and please don't get it wrong but iam very
curious why people still use C instead of other languages especially C++.
i heard people say C++ is slower than C but i can't believe that. in pieces
of the application where speed really matters you can still use "normal"
functions or even static methods which is basically the same.
in C there arent the simplest things present like constants, each struct and
enum...
|
by: Mark L Pappin |
last post by:
<puts on Compiler Vendor hat>
I've recently discovered that our compilers don't
make any attempt to handle floating point overflow in add/subtract/
multiply/divide, with the result that programmers who don't range-
check their data can e.g. multiply two very tiny values and end up
with a very large one. This is (AFAICT) quite fine according to the
Standard but is certainly a QoI issue and I'd like to raise ours.
I believe that it's...
|
by: 63q2o4i02 |
last post by:
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...
| |
by: Steven D'Aprano |
last post by:
I'm looking for some way to get the next floating point number after any
particular float.
(Any mathematicians out there: I am aware that there is no "next real
number". But floats are not real numbers, they only have a finite
precision.)
According to the IEEE standard, there should be a routine like next(x,y)
which returns the next float starting from x in the direction of y.
|
by: vendredi5h |
last post by:
Hello all,
I'd like to split a 64-bits word (hold as a floating point number) into
two 32-bits words (hold as integers). Bitwise operators are working on
Integers, not on floating point.
Anyone can tell me how I can do this?
Yannick
|
by: dis_is_eagle |
last post by:
hi....i have encountered strange problem regarding floating point
comparison...the problem is...
main()
{
float a=0.7;
if(0.7 a)
printf("hi");
else
printf("hello");
|
by: Mukesh_Singh_Nick |
last post by:
Why does floating point have a rounding error? How to work around it?
For example, the following:
flaot f = 1234.12345678F;
printf("%2f\n", f) //prints 1234.123413
and
|
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...
|
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...
| |
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,...
|
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...
|
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...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
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
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
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...
| |