PocketMatrix forums

A read-only archive of the PocketMatrix forums (2001–2014). Posting and accounts are closed.

Binary

How the hell do you specify a number as binary in C++?

0x for hex...and?
01010101
1, 2, 4, 8, 16, 32, 64, 128
so I just typed in the number 170... I'm not sure if that's what you mean, but it might be.
You can't. You have to enter them as Hex, Decimal or Octal.

Dan East
Thanks Dan, I went digging and saw that myself.

You'd think after coding for 19 years I'd know that...

As for Moose, thanks for the binary lesson.
It would be possible to create a macro to convert binary to hex or decimal during preprocessing.

What the heck, give this a shot. It's off the top of my head, and a simpler solution may be available. This will only convert a 4 digit binary value to decimal, but of course can be extended to handle more bits. The limit would be 10 bits, otherwise the pseudo-binary input integer would be larger than what can be stored in a 32 bit signed int.
Code:

#define bin2int(b) (b&1)|(((b/10)&1)<<1)|(((b/100)&1)<<2)|(((b/1000)&1)<<3)

int i=bin2int(1101);

Dan East
It looks like the syntactic coloring script isn't handling that quite right. I guess I'll have to tweak that now. Dangit. :)

Dan East
well it is only version 0.1, Dan. Not even you, the almighty Dan East, can do it perfect the first time.
If you're not in a hurry, this will work:

#define BINARY(b) _tcstoul(TEXT(#b), NULL, 2)
In case anyone isn't familiar with preprocessor directives, there's a big difference between Digby's version and mine. The definition I provided converts the binary value at compilation time into an int. Thus there is no overhead at runtime, and the end result is exactly the same as entering the value in hex manually in the first place. Digby's example requires a function be called at runtime to convert the binary string each time it is accessed. That's what he means about not being in a hurry. :)

Dan East