473,387 Members | 1,549 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.

Basic question about casting and addresses

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(const 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(float);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?
Jul 19 '05 #1
4 2489
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(const 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(float);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

Jul 19 '05 #2
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(const 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(float);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

Jul 19 '05 #3

"drowned" <vo**********@hotmail.com> wrote in message
news:6d**************************@posting.google.c om...
....
int main() {
float f=1;
unsigned char uc = (unsigned char) &f;
unsigned char* ucp = &uc;
for(int i=0;i<sizeof(float);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
Jul 19 '05 #4
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(const 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_cast<unsigned char*>(&f);
for(int i=0;i<sizeof(float);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.
Jul 19 '05 #5

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

Similar topics

28
by: Yacine | last post by:
Does anyone know why void main(){ double x; double *y; (int) y = x; } compiles well, and why
231
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...
10
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;...
20
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...
14
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...
8
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
6
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. ...
9
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
11
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,...
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: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
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: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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
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.