I have to do this : define a float variable and take its adress,cast that to an unsigned char and assign to it to an unsigned char pointer:
Why isnt this good ?

float f;

  unsigned char* c = static_cast<unsigned char>(&f);

Recommended Answers

All 2 Replies

I think you are supposed to use reinterpret_cast for this, but it doesn't work (surely I'm doing something wrong)

#include <iostream>

int main () 
{
  float f = 2;

  unsigned char* c = reinterpret_cast<unsigned char*>(&f);
  std::cout << (int)*c << std::endl;
  
  return 0;
}

It outputs 0 when I would expect 2.

>It outputs 0 when I would expect 2.
The problem is with your expectation. You're punning the bytes of a multi-byte object(float) to raw binary[1], then casting the first byte[2] of the result to another multi-byte type (int) and somehow expecting the value to match what was originally stored in the original multi-byte object. This is ignoring the non-trivial byte representation of floating-point that doesn't map well to integers in a direct conversion.

Might I suggest inspecting the bytes directly instead?

#include <cstddef>
#include <iostream>
#include <limits>
#include <bitset>

int main() 
{
    using namespace std;

    float f = 2;

    // Pun to raw binary
    unsigned char* c = reinterpret_cast<unsigned char*>(&f);

    // Display the byte representation of f
    for (size_t i = 0; i < sizeof(float); i++)
        cout<< bitset<numeric_limits<unsigned char>::digits>(c[i]) <<' ';
    std::cout<<'\n';

    // Do a round trip back to float
    std::cout<< *reinterpret_cast<float*>(c) << '\n';
}

[1] An array or pointer to unsigned char is as close as you get in C++.
[2] Note that the "first" byte depends on the endianness of the representation.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.