473,387 Members | 1,515 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

how the following code works?

main() {
float a = 5.375;
char *p;
int i;
p = (char*)&a;
for(i=0;i<=3;i++)
printf("%02x",(unsigned char)p);
}

the above code gives the binary representation of a.
how does it work?

Jun 16 '07 #1
16 1664
In article <11*********************@e9g2000prf.googlegroups.c om>,
Ravi <ra*********@gmail.comwrote:
>main() {
float a = 5.375;
char *p;
int i;
p = (char*)&a;
for(i=0;i<=3;i++)
printf("%02x",(unsigned char)p);
}

the above code gives the binary representation of a.
how does it work?
It doesn't.
dave
(it appears to be an attempt to examine the bytes representing an object
of floating-point types, but contains at least one obvious error, one
subtle error, and one gratuitious assumption.)

--
Dave Vandervies dj******@csclub.uwaterloo.ca
P.J. Plauger has a valid reason [...] although I would say that was
more to do with his customers being less than sensible.
--Flash Gordon in comp.lang.c
Jun 16 '07 #2
Ravi wrote:
>
main() {
float a = 5.375;
char *p;
int i;
p = (char*)&a;
for(i=0;i<=3;i++)
printf("%02x",(unsigned char)p);
}

the above code gives the binary representation of a.
how does it work?
It doesn't work at all.

/* BEGIN new.c */

#include <stdio.h>

int main(void)
{
float a = 5.375;
unsigned char *p;
size_t i;

p = (unsigned char *)&a;
for (i = 0; i != sizeof a; ++i) {
printf("%02x ", p[i]);
}
putchar('\n');
return 0;
}

/* END new.c */
--
pete
Jun 16 '07 #3

"Ravi" <ra*********@gmail.comwrote in message
news:11*********************@e9g2000prf.googlegrou ps.com...
main() {
float a = 5.375;
char *p;
int i;
p = (char*)&a;
for(i=0;i<=3;i++)
printf("%02x",(unsigned char)p);
}

the above code gives the binary representation of a.
how does it work?
Let's rewrite slightly more professionally.

#include <stdio.h>

void dump(void *bytes, int N)
{
int i;
unsigned char *cbytes = bytes;

for(i=0;i<N;i++)
printf("%02x", cbytes[i]);
printf("\n");
}

int main(void)
{
float a = 123.567;

dump(&a, sizeof(float));
return 0;
}

Now you ought to see how the program works. Plus you have a handy little
routine you can cut and paste any time you need to examine an object's
binary representation.

--
Free games and programming goodies.
http://www.personal.leeds.ac.uk/~bgy1mm

Jun 16 '07 #4
On Jun 16, 10:38 am, Ravi <ra.ravi....@gmail.comwrote:
main() {
float a = 5.375;
char *p;
int i;
p = (char*)&a;
for(i=0;i<=3;i++)
printf("%02x",(unsigned char)p);

}
oops, you had taken liberty over the size of float!
>printf("%02x",(unsigned char)p);
Never know what you are trying to do by this statement.
>
the above code gives the binary representation of a.
No, it doesn't!
Moreover, even if you correct all the mistakes, I don't think you will
get the binary representation, unless CHAR_BIT==1,in which case your
implementation is non-conforming!

You will get only "byte representation".
how does it work?
It doesn't work at all.
Jun 16 '07 #5
Ravi said:
main() {
float a = 5.375;
char *p;
int i;
p = (char*)&a;
for(i=0;i<=3;i++)
printf("%02x",(unsigned char)p);
}

the above code gives the binary representation of a.
how does it work?
It doesn't.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Jun 16 '07 #6

"pete" <pf*****@mindspring.comha scritto nel messaggio
news:46**********@mindspring.com...
Ravi wrote:
>>
main() {
float a = 5.375;
char *p;
int i;
p = (char*)&a;
for(i=0;i<=3;i++)
printf("%02x",(unsigned char)p);
}

the above code gives the binary representation of a.
how does it work?

It doesn't work at all.

/* BEGIN new.c */

#include <stdio.h>

int main(void)
{
float a = 5.375;
unsigned char *p;
size_t i;

p = (unsigned char *)&a;
for (i = 0; i != sizeof a; ++i) {
Any reason to use != where the rest of the world uses <?
(Just curious, I know that *here* they do the same.)
printf("%02x ", p[i]);
}
putchar('\n');
return 0;
}

/* END new.c */
--
pete

Jun 16 '07 #7
Army1987 wrote:
"pete" <pf*****@mindspring.comha scritto nel messaggio
news:46**********@mindspring.com...
> for (i = 0; i != sizeof a; ++i) {
Any reason to use != where the rest of the world uses <?
(Just curious, I know that *here* they do the same.)
In such constructs I usually put != instead of < as well. It doesn't matter
here, and it's the same thing that would be required in just a slightly
different example:
for (p = start; p != NULL; p = p->next)
Jun 16 '07 #8
In article <f5**********@tdi.cu.mi.it>, Army1987 <pl********@for.itwrote:
> for (i = 0; i != sizeof a; ++i) {
>Any reason to use != where the rest of the world uses <?
There is a theory that it's better to use "<", because if the variable
somehow gets to be bigger than the terminating value, the loop will
still stop. I believe this is sometimes considered to be "defensive
programming".

There is another theory that this is a really bad idea, because it will
hide bugs in your program (how did the variable get the bogus value?),
and you should instead use "!=" to make the error get noticed sooner.

From the point of view of readability, I think that "<" is more likely to
express the way the programmer is thinking about it - the terminating
value expresses the end of a range, rather than a sentinel value as
is "while(*p++ != '\0')".

So using "!=" seems to me to be in the same class of idioms as writing
"if(1 == a)" rather than "if(a == 1)" - it might sometimes result in
earlier error detection, but at the expense of naturalness and hence
readability.

-- Richard
--
"Consideration shall be given to the need for as many as 32 characters
in some alphabets" - X3.4, 1963.
Jun 16 '07 #9
Harald van D?k wrote:
>
Army1987 wrote:
"pete" <pf*****@mindspring.comha scritto nel messaggio
news:46**********@mindspring.com...
for (i = 0; i != sizeof a; ++i) {
Any reason to use != where the rest of the world uses <?
(Just curious, I know that *here* they do the same.)

In such constructs I usually put != instead of < as well. It doesn't matter
here, and it's the same thing that would be required in just a slightly
different example:
for (p = start; p != NULL; p = p->next)
'<' is safer. If something glitches the value of i.

--
<http://www.cs.auckland.ac.nz/~pgut001/pubs/vista_cost.txt>
<http://www.securityfocus.com/columnists/423>
<http://www.aaxnet.com/editor/edit043.html>
cbfalconer at maineline dot net

--
Posted via a free Usenet account from http://www.teranews.com

Jun 16 '07 #10
In article <46***************@yahoo.com>,
CBFalconer <cb********@maineline.netwrote:
>'<' is safer. If something glitches the value of i.
Why is it safer for a loop to finish and the program continue if the
value of a variable has been "glitched"?

In many cases, having the loop continue so that the program gets a
segmentation fault seems safer.

-- Richard
--
"Consideration shall be given to the need for as many as 32 characters
in some alphabets" - X3.4, 1963.
Jun 16 '07 #11
Richard Tobin wrote:
CBFalconer <cb********@maineline.netwrote:
>>'<' is safer. If something glitches the value of i.

Why is it safer for a loop to finish and the program continue if
the value of a variable has been "glitched"? In many cases,
having the loop continue so that the program gets a segmentation
fault seems safer.
Say the loop just performs a fairly lengthy calculation. If i gets
above the terminal value things can go on for 2^32 iterations.
You'll probably never find it, because the use will assume a system
crash. Obviously the optimum depends on the situation.

--
<http://www.cs.auckland.ac.nz/~pgut001/pubs/vista_cost.txt>
<http://www.securityfocus.com/columnists/423>
<http://www.aaxnet.com/editor/edit043.html>
cbfalconer at maineline dot net

--
Posted via a free Usenet account from http://www.teranews.com

Jun 16 '07 #12
In article <46***************@yahoo.com>,
CBFalconer <cb********@maineline.netwrote:
>Say the loop just performs a fairly lengthy calculation. If i gets
above the terminal value things can go on for 2^32 iterations.
You'll probably never find it, because the use will assume a system
crash.
Huh? Why would the user assume the system has crashed just because
some program does not terminate?
>Obviously the optimum depends on the situation.
Yes, certainly. For the programs I write as part of my work, I would
much prefer a segmentation fault or non-termination to termination
with an undetected incorrect answer, because the aim of the program is
to find the right answer. But there are other situations: for a
computer game crashing may be the most annoying outcome for the user.

I conclude that there is no general rule on safety grounds for whether
to choose "<" or "!=" as a loop termination test. So I just write
whatever seems most natural.

-- Richard
--
"Consideration shall be given to the need for as many as 32 characters
in some alphabets" - X3.4, 1963.
Jun 16 '07 #13
Richard Tobin wrote:
CBFalconer <cb********@maineline.netwrote:
>Say the loop just performs a fairly lengthy calculation. If i gets
above the terminal value things can go on for 2^32 iterations.
You'll probably never find it, because the use will assume a system
crash.

Huh? Why would the user assume the system has crashed just because
some program does not terminate?
Well, I would.
>
>Obviously the optimum depends on the situation.

Yes, certainly. For the programs I write as part of my work, I would
much prefer a segmentation fault or non-termination to termination
with an undetected incorrect answer, because the aim of the program is
to find the right answer. But there are other situations: for a
computer game crashing may be the most annoying outcome for the user.

I conclude that there is no general rule on safety grounds for whether
to choose "<" or "!=" as a loop termination test. So I just write
whatever seems most natural.
Another thing, you can check the termination condition after exit
easily, with something like "if (i != endvalue) makenoises(...);",
and not disturb the normal running. Now you can make the message
detailed.

--
<http://www.cs.auckland.ac.nz/~pgut001/pubs/vista_cost.txt>
<http://www.securityfocus.com/columnists/423>
<http://www.aaxnet.com/editor/edit043.html>
cbfalconer at maineline dot net

--
Posted via a free Usenet account from http://www.teranews.com

Jun 17 '07 #14
Army1987 wrote:
>
"pete" <pf*****@mindspring.comha scritto nel messaggio
news:46**********@mindspring.com...
for (i = 0; i != sizeof a; ++i) {
Any reason to use != where the rest of the world uses <?
(Just curious, I know that *here* they do the same.)
I consider != to be conceptually simpler than <

--
pete
Jun 17 '07 #15
pete wrote:
Army1987 wrote:
>>
"pete" <pf*****@mindspring.comha scritto nel messaggio
news:46**********@mindspring.com...
for (i = 0; i != sizeof a; ++i) {
Any reason to use != where the rest of the world uses <?
(Just curious, I know that *here* they do the same.)

I consider != to be conceptually simpler than <
Yes, but if the increment is changed to i+=2 then the above
loop will never terminate if "sizeof a" is odd. Using less
than will not have the same problem.

Erik
--
-----------------------------------------------------------------
Erik de Castro Lopo
-----------------------------------------------------------------
Gambling(n): A discretionary tax on those asleep during high school
maths.
Jun 17 '07 #16

"Richard Tobin" <ri*****@cogsci.ed.ac.ukha scritto nel messaggio
news:f5***********@pc-news.cogsci.ed.ac.uk...
In article <46***************@yahoo.com>,
CBFalconer <cb********@maineline.netwrote:
>>'<' is safer. If something glitches the value of i.

Why is it safer for a loop to finish and the program continue if the
value of a variable has been "glitched"?

In many cases, having the loop continue so that the program gets a
segmentation fault seems safer.
for (i = 0; i < n; i++) {
do_stuff();
}
assert(i == n);
Jun 17 '07 #17

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

Similar topics

3
by: Peter Rohleder | last post by:
Hi, I'm using a style-sheet where I make use of the XPATH-"following-sibling"-expression. The part which makes problems looks similar to the following code: --------------------------- ...
1
by: Marlon | last post by:
<! -- Web.config--> <authentication mode="Windows" /> <identity impersonate="true" /> <! -- Web.config--> where Configurations.ADsUsersPath is...
1
by: Balaji. M. | last post by:
Hi, The following code not works in netscape 7.2, function WizardMoveNext () { CurrentStep++; WizardPage = "regreqstep" + CurrentStep + ".php"; alert ("Current Wizard Page " + WizardPage);...
8
by: aditya | last post by:
hi, Can anybody please tell me that how the following printf(...) statement works- main(){ int d=9; printf("%d",printf("%d")); return 0;
0
by: Kathy Burke | last post by:
I'm providing the following syntax in hopes someone could tell me why I get an object reference error on the second one. The first one works, using an xmlDocument, the second one immediately...
13
by: Just Me | last post by:
The following almost works. The problem is Marshal.PtrToStringAuto seems to terminate at the first null so I don't get the full string. Any suggestions on how to fix this? Or how to improve the...
1
by: Jedufa | last post by:
following of thread: "Adding namespaces to code behind automatically" Hello, I had quite the same problem and got further in the right direction with your suggestions, thanks. Nevertheless, I...
4
by: zaperaj | last post by:
Im working with python2.2 on red hat linux. The following program is supposed to print decreasing numbers from an entered number till 1, each decrement being = 1 : #! usr/bin/env/python def...
2
by: SRT | last post by:
Hi, I have the following code below, which works if I do the following Call No1 'Call No2 Exit Sub For whatever reason it fails at Me!.SetFocus at the end of Sub No2 with
6
by: dba | last post by:
using the following code with a problem.... echo "<input type='hidden' name='member_id' value=\"{$row}\">{$row}"; echo "<input type='radio' name='member_name' value=\"{$row}\">{$row}<br />"; ...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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...
0
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,...
0
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...

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.