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.
|