I'm having a problem understanding why the code in this little program
I've got is behaving the way it does... if anyone can explain it, I'd
be grateful:
#include <iostream>
using namespace std;
//This function takes an unsigned char (one byte on my machine)
//and prints it in binary notation
void printBinary(con st unsigned char val) {
for(int i = 7; i >= 0; i--)
if(val & (1 << i))
std::cout << "1";
else
std::cout << "0";
}
int main() {
float f=1;
unsigned char uc = (unsigned char) &f;
unsigned char* ucp = &uc;
for(int i=0;i<sizeof(fl oat);i++) { //sizeof(float) == 4
cout << "ucp[" << i << "] = " << (long)ucp[i] << endl;
cout << "ucp[" << i << "] = "; printBinary(ucp[i]); cout << endl;
}
}
If I understand what is going on here correctly, I am taking the
address of the float and casting it to an unsigned char. I then assign
that value to the unsigned char pointer. When I change the value of
the float, however, ucp's value changes. I would think that ucp would
not change because it holds an address... what does changing the value
of the float have to do with its address? 4 2502
drowned wrote: I'm having a problem understanding why the code in this little program I've got is behaving the way it does... if anyone can explain it, I'd be grateful:
#include <iostream> using namespace std;
//This function takes an unsigned char (one byte on my machine) //and prints it in binary notation void printBinary(con st unsigned char val) { for(int i = 7; i >= 0; i--) if(val & (1 << i)) std::cout << "1"; else std::cout << "0"; }
int main() { float f=1; unsigned char uc = (unsigned char) &f; unsigned char* ucp = &uc; for(int i=0;i<sizeof(fl oat);i++) { //sizeof(float) == 4 cout << "ucp[" << i << "] = " << (long)ucp[i] << endl; cout << "ucp[" << i << "] = "; printBinary(ucp[i]); cout << endl; } }
Let's see how memory *might* be layed out:
stack_frame : <return address 0>
stack_frame : <return address 1>
stack_frame : <return address 2>
stack_frame : <return address 3>
f : <float byte 0>
f : <float byte 1> <<<<<<<<<< 3 + &uc
f : <float byte 2> <<<<<<<<<< 2 + &uc
f : <float byte 3> <<<<<<<<<< 1 + &uc
uc : <char byte 0> <<<<<<<<<< &uc
filler : <random junk>
filler : <random junk>
filler : <random junk>
ucp : <unsigned char* byte 0>
ucp : <unsigned char* byte 1>
ucp : <unsigned char* byte 2>
ucp : <unsigned char* byte 3>
&uc + 3 bytes is within the float.
If I understand what is going on here correctly, I am taking the address of the float and casting it to an unsigned char. I then assign that value to the unsigned char pointer. When I change the value of the float, however, ucp's value changes. I would think that ucp would not change because it holds an address... what does changing the value of the float have to do with its address?
What your doing is undefined because you take the address of an object
of size 1 and then reference 3 more objects after that. Who knows what
the compiler should or would or has done or not done. What I
demonstrated above is what *SOME* compilers do but it's not even correct
because some compilers *may* not decide to layout memory in this way.
In other words - DON'T do it.
G
drowned wrote: I'm having a problem understanding why the code in this little program I've got is behaving the way it does... if anyone can explain it, I'd be grateful:
#include <iostream> using namespace std;
//This function takes an unsigned char (one byte on my machine)
A char is a byte on all machines. This is required by the C++ standard.
//and prints it in binary notation void printBinary(con st unsigned char val) { for(int i = 7; i >= 0; i--) if(val & (1 << i)) std::cout << "1"; else std::cout << "0"; }
int main() { float f=1; unsigned char uc = (unsigned char) &f;
This is not a very meaningful thing to do. The result is very unlikely
to be the address of f, or anything useful for that matter. Also, using
C-style casts is not recommended in most cases. Use C++ cast operators
instead.
unsigned char* ucp = &uc; for(int i=0;i<sizeof(fl oat);i++) { //sizeof(float) == 4 cout << "ucp[" << i << "] = " << (long)ucp[i] << endl; cout << "ucp[" << i << "] = "; printBinary(ucp[i]); cout << endl; } } If I understand what is going on here correctly, I am taking the address of the float and casting it to an unsigned char. I then assign that value to the unsigned char pointer.
No. You assign the address of your unsigned char (uc) to your unsigned
char pointer (ucp).
When I change the value of the float, however, ucp's value changes.
I don't know of any reason this would happen, and I see no evidence for
it in the code you posted. Post code demonstrating this if you'd like it
explained.
I would think that ucp would not change because it holds an address... what does changing the value of the float have to do with its address?
Nothing. There does not appear to be any relationship at all between the
float f and the unsigned char * ucp.
-Kevin
"drowned" <vo**********@h otmail.com> wrote in message
news:6d******** *************** ***@posting.goo gle.com...
.... int main() { float f=1; unsigned char uc = (unsigned char) &f; unsigned char* ucp = &uc; for(int i=0;i<sizeof(fl oat);i++) { //sizeof(float) == 4 cout << "ucp[" << i << "] = " << (long)ucp[i] << endl; cout << "ucp[" << i << "] = "; printBinary(ucp[i]); cout << endl; } }
You probably mean
unsigned char* ucp = (unsigned char *)&f;
--
Roger
drowned wrote: I'm having a problem understanding why the code in this little program I've got is behaving the way it does... if anyone can explain it, I'd be grateful:
#include <iostream> using namespace std;
//This function takes an unsigned char (one byte on my machine)
An unsigned char _always_ is one byte. Note however that a byte may be
bigger than 8bits.
//and prints it in binary notation void printBinary(con st unsigned char val) { for(int i = 7; i >= 0; i--) if(val & (1 << i)) std::cout << "1"; else std::cout << "0"; }
int main() { float f=1; unsigned char uc = (unsigned char) &f;
Here, you convert the address of f into an unsigned char. Of course
parts of that address will probably be lost, since on most machines,
pointers are bigger than unsigned chars.
unsigned char* ucp = &uc;
Here, you create a pointer that points to the converted address (or what
is left from it), which is one byte big. I'm quite sure that you wanted
instead to convert the address of the float into a pointer to unsigned
char, for which you'd have to replace your above two lines with:
unsigned char* ucp = reinterpret_cas t<unsigned char*>(&f);
for(int i=0;i<sizeof(fl oat);i++) { //sizeof(float) == 4 cout << "ucp[" << i << "] = " << (long)ucp[i] << endl; cout << "ucp[" << i << "] = "; printBinary(ucp[i]); cout << endl; }
In that loop, you try to read 4 bytes through the above pointer, which
only points to one single unsigned char.
} If I understand what is going on here correctly, I am taking the address of the float and casting it to an unsigned char.
Yes.
I then assign that value to the unsigned char pointer.
No, you assign the address of the resulting unsigned char to the
unsigned char pointer.
When I change the value of the float, however, ucp's value changes. I would think that ucp would not change because it holds an address...
How do you change it?
what does changing the value of the float have to do with its address?
Nothing, I'd say. This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Yacine |
last post by:
Does anyone know why
void main(){
double x;
double *y;
(int) y = x;
}
compiles well, and why
|
by: Brian Blais |
last post by:
Hello,
I saw on a couple of recent posts people saying that casting the return
value of malloc is bad, like:
d=(double *) malloc(50*sizeof(double));
why is this bad? I had always thought (perhaps mistakenly) that the
purpose of a void pointer was to cast into a legitimate date type. Is
this wrong? Why, and what is considered to be...
|
by: Kieran Simkin |
last post by:
Hi,
I wonder if anyone can help me, I've been headscratching for a few hours
over this.
Basically, I've defined a struct called cache_object:
struct cache_object {
char hostname;
char ipaddr;
};
|
by: j0mbolar |
last post by:
I was reading page 720 of unix network programming,
volume one, second edition. In this udp_write function
he does the following:
void udp_write(char *buf, <everything else omitted)
struct udpiphdr *ui;
struct ip *ip;
ip = (struct ip *) buf;
|
by: Mirko |
last post by:
Hello, I'm new to this list and to Usenet in general,
so please forgive (and advice) me, if I do something wrong.
Anyway.
I am a bit confused, because I always thought one
_should_ explicitly cast the void* pointer returned by malloc.
Now I read postings saying that this is dangerous.
Could somebody please clearify this?
| |
by: windandwaves |
last post by:
Hi Folk
I want to send out a basic newsletter from my MySql database of contacts.
Does anyone know a nice and simple bit of PHP that allows me to do this?
TIA
- Nicolas
|
by: Ken Fine |
last post by:
This is a basic question. What is the difference between casting and using
the Convert.ToXXX methods, from the standpoint of the compiler, in terms of
performance, and in other ways? e.g.
this.ContentID = (int)ci.Conid;
vs.
this.ContentID = Convert.ToInt32(ci.Conid);
I tend to use the latter form because it seems more descriptive to me,...
|
by: Taras_96 |
last post by:
Hi everyone,
I was experimenting with static_cast and reinterpret cast
#include <iostream>
struct A1 { int a; };
struct A2 { double d; };
struct B : public A1, A2
|
by: =?Utf-8?B?UGV0ZXIgSw==?= |
last post by:
I am working with Visual Studio or alternately with Expression Web. I need
to create about 50 aspx pages with about 1200 thumbnali images, typically
arranged in three to four groups per page, having hyperlinks to the
corresponding full size images.
Can anybody point me to locations in MSDN or elsewhere giving the references
to attach, the...
|
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...
|
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. ...
| |
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...
|
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...
|
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...
|
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...
|
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.
| |