开发者

Regarding number representation

开发者_StackOverflow中文版How do I find the representation of a Number for the system I am on?


AFAIK every modern computer uses binary when representing a number. Experiments have been made with other kind of computers, but they have failed to compete with binary.

However, they are working a quantum computers which work completely different and represent numbers on a completely different way.


The usual way is to store the number in memory, and then inspect the memory.

volatile number_type x;
x = 512.123;

typedef unsigned char const volatile uccv;
uccv *c = reinterpret_cast< uccv * >( & x );
std::cout << std::hex;
std::cout.fill( '0' );
for ( uccv *pen = c; pen != c + sizeof x; ++ pen ) {
    std::cout.width( 2 );
    std::cout << static_cast< unsigned >( * pen );
}
std::cout << std::dec << '\n';

Apologies for the volatile; I do not recall strict aliasing rules and don't want to look them up right now.


To know the sign representation is actually quite simle. Look at the result of

(favoriteType)-1 & (favoriteType)3 

Once you have understood how the three different sign representations work that C allows (see eg. Acme's answer), you will easily work out the values of such an expression for them.


Architectural questions such as representation (word size, two's- vs. one's-complement vs. sign-magnitude) and endianness are best answered with hardware and/or OS and/or compiler documentation.

You can use type punning to examine the individual bytes of a value:

T value = ...; // for some numeric type T (int, short, long, double, float, etc.)
unsigned char *p = (unsigned char*) &value;
size_t i;

printf("%10s%8s\n", "address", "value");
printf("%10s%8s\n", "-------", "-----");
for (i = 0; i < sizeof value; i++)
  printf("%10p%8x\n", p+i, (unsigned int) p[i]);

For big- vs. little-endian, you could do something like

unsigned int value = 0x01;
unsigned char *p = (unsigned char *) &value;
if (p[0] == 1)
  printf("Little-endian\n");
else if (p[sizeof value - 1] == 1)
  printf("Big-endian\n");
else
  printf("Weird\n");

Better to RTM, though.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜