1

I think if some integer is in register by scanf, then the number would be in 2s complement representation. Can I get that number by printf? I searched many websites but couldnt find the code for C beginners...

  • 3
    Welcome to Stack Overflow! Your question is a bit vague - can you try to explain better what you're trying to do? Showing some code is usually helpful in telling us what the question is. In particular, the phrases "float" and "2's complement" aren't usually seen together. – Carl Norum Nov 06 '12 at 05:49
  • `float` doesn't use a 2's complement internally nor does the wikipedia article about 2's complement even mention the use for non-integers. – John Dvorak Nov 06 '12 at 05:51
  • http://stackoverflow.com/q/111928/1689451 – Rudolf Mühlbauer Nov 06 '12 at 06:05

2 Answers2

0

Float numbers are not stored in 2's complement, but rather in IEEE 754. To print the binary representation of some binary data, first see https://stackoverflow.com/a/112956/1689451. You can put your float into a union to extract the single bytes:

#include <stdio.h>      /* printf */
#include <string.h>     /* strcat */

// taken from https://stackoverflow.com/a/112956/1689451
const char *byte_to_binary(int x)
{
    static char b[9];
    b[0] = '\0';

    int z;
    for (z = 128; z > 0; z >>= 1)
    {
        strcat(b, ((x & z) == z) ? "1" : "0");
    }

    return b;
}

union {
  float f;
  unsigned char b[4];
} x;

x.f = 0.34;
for (int i = 0; i < 4; i++) {
  printf("%s", byte_to_binary(x.b[i]));
}

I did not try the example; does probably not compile, but should give hints in the right direction.

Community
  • 1
  • 1
Rudolf Mühlbauer
  • 2,511
  • 16
  • 18
0

There's no standard in c that prints "two's complement" number or binary numbers in general, if that's your question. That task must be solved separately. Eg.

for (i=0;i<32;i++) putc( '0'+((number >> (31-i)) & 1)); // or copy to local strings

Otherwise scanf("%f", &my_float); prints with printf("%f", my_float);

Aki Suihkonen
  • 19,144
  • 1
  • 36
  • 57