Negative number system as compile-time constant?

F

Frederick Gotham

(I'm not sure if there's already something in the Standard Library for
doing this... ?)

Is the following macro okay for getting a compile-time constant that
indicates which negative number system the machine uses?

#define NUM_SYS ( -1 & 1 ? -1 & 2 ? TWOS : SIGNMAG : ONES )


How it works:

(1) Firstly, it gets -1, which will either be:

1000 0001 Sign-mag
1111 1110 One's complement
1111 1111 Two's complement

(2) It AND's it with 1. If the result is false, then we've got one's
complement (as you can see from the bit-pattern above).

(3) It then AND's it with 2. If the result is true, then we have two's
complement. Otherwise, it's sign-magnitude.


Possibly used something like as follows:

#define SIGNMAG "Sign-Magnitude"
#define ONES "One's complement"
#define TWOS "Two's complement"

#define NUM_SYS ( -1 & 1 ? -1 & 2 ? TWOS : SIGNMAG : ONES )

#include <stdio.h>
#include <stdlib.h>

int main()
{
printf( "This machine uses: %s\n", NUM_SYS );

system("PAUSE");
}



Another thing, I naively tried to do the following in my original code:


puts( "This machine uses: " NUM_SYS );


thinking that NUM_SYS would become a string literal which would sit right
beside the one to its left (yielding one string literal, i.e:)

puts( "This machine uses: " "Two's complement" );


I wonder if there's any way of getting that to work... ? Hmm...
 
C

Christoph Scholtes

Hi Pete,
#if -1 & 3 == 1
#define NUM_SYS SIGNMAG
#elif -1 & 3 == 2
#define NUM_SYS ONES
#else
#define NUM_SYS TWOS
#endif

#define SIGNMAG "Sign-Magnitude"
#define ONES "One's complement"
#define TWOS "Two's complement"

Is there a specific reason to use the second block of defines instead of
putting them in the according lines above, like #define NUM_SYS
"Sign-Magnitude"?

Chris
 
F

Frederick Gotham

Christoph Scholtes posted:
Hi Pete,


Is there a specific reason to use the second block of defines instead of
putting them in the according lines above, like #define NUM_SYS
"Sign-Magnitude"?


Style. Same reason why someone writes:

const char *p;

instead of:

char const* p;


Another thing is that we can re-use the macros, e.g.:

puts( "My system is " NUM_SYS ", but I'd rather it were " TWOS "." );
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,535
Members
45,008
Latest member
obedient dusk

Latest Threads

Top