0

I want to print the binary value of a given float just by directly accessing the memory I used this code to access the value of an int

int var = 34;

int *ptr;

ptr = &var;


printf("\nDirect access, variable var value = var = %d", var);

i am wondering how to access the memory amount of a float and print it

  • here is everything `int` – Rustam Oct 06 '14 at 07:35
  • @JimBalter my question is accessing the memory amount of float by accessing the memory not converting it to binary or hex – Morteza Azmoodehafshar Oct 06 '14 at 07:43
  • 1
    Er, did you even read the link, which gives a similar solution as the one you accepted below? You asked, plain as day, "how to print binary value of float in c". You later write "i am wondering how to access the memory amount of a float" -- a totally different question, and the answer is `sizeof(float)`. – Jim Balter Oct 06 '14 at 07:56
  • P.S. The code you posted sets `ptr` but never uses it, and it prints a decimal representation of var, not a "binary value". The equivalent code for float would be `float var = 34.56; printf("\nDirect access, variable var value = var = %f", var);` – Jim Balter Oct 06 '14 at 08:06

1 Answers1

4

Use a union:

typedef union {
    float f;
    uint8_t a[sizeof(float)];
} U;

Then print it like this:

U u = { 42.0f };

for (int i = 0; i < sizeof(float); ++i)
{
    printf("%02x", u.a[i]);
}

Note that this is technically implementation-defined behaviour in C89 (although it is unlikely to fail even with a C89 compiler), but it is perfectly OK in C99 and C11 - see this post for further details.

Community
  • 1
  • 1
Paul R
  • 208,748
  • 37
  • 389
  • 560
  • FWIW, that's undefined behavior. – Jim Balter Oct 06 '14 at 07:31
  • Is it a conversion of float to binary or directly accessing the memory? – Morteza Azmoodehafshar Oct 06 '14 at 07:41
  • @JimBalter: only in C89, and even then it is unlikely to cause problems - see edit to answer above. – Paul R Oct 06 '14 at 07:43
  • @MortezaAzmoodehafshar: the union maps a float to a byte array, allowing the same chunk of memory to be interpreted as either type. – Paul R Oct 06 '14 at 07:44
  • I think this is a conversion of a float to hex but i want to print it by accessing the memory – Morteza Azmoodehafshar Oct 06 '14 at 07:44
  • 2
    @MortezaAzmoodehafshar: you are "accessing the memory" - the example above just shows how to access the memory and display the contents as hex, but you can do whatever you like with it. Read up on `union`s. – Paul R Oct 06 '14 at 07:45
  • 1
    "I think this is a conversion of a float to hex" -- float is a type; hex is a representation ... there's no "conversion" between them. A float can be represented in a number of ways; the typical way is to use %f to get a decimal fraction. Another way is to print it as several hex bytes, which is what Paul's code does ... which clearly accesses the memory ... how else could it produce a value? – Jim Balter Oct 06 '14 at 08:03