How to specify binary number format?

Go To Last Post
8 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Didn't expect to be asking one this simple, but after three 'C' reference books and numerous scans of example code, I can't figure out how to specify that a number is binary. Do C programmers even use binary?

I'm getting warning "large integer implicitly truncated to unsigned type", so I assume my number 01000000 is being taken as decimal. I've tried a b in front, a b at the end, and a % in front, based on various assembler experiences. Just causes even more errors.

Thanks,

Nick :cry:

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Hi,

Instead of using 0x for hex, use 0b for binary:

unsigned int MyInt = 0b1010101010101;

Good luck,

Alan

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

That's it. Thanks, Alan.

Nick

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Hi,

Sure thing! :)

Alan

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

... except it's a non-standard gcc extension.

JW

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

nickkennedy wrote:
I assume my number 01000000 is being taken as decimal.

Since you start the number with 0, it should be taken as octal number, not decimal. Been shot myself in foot once with this one.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Personally I'd just get into the habit of mentally converting to hex. Take 01000000 and break it into groups of 4 from the right then translated to hex. It becomes 0100 0000 which is then 0x40.

(hopefully most programmers can count from 0x0 (0000) to 0xF (1111)!)

Going the other way a programmer would hopefully recognise that 0xAE is 1010 1110 or 0b10101110

While it's great that Joerg got "0b" added to avr-gcc I wouldn't start relying on it as you'll be bitten when you move to other CPUs or compilers.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

It would be nice if the 0b thing was standard in C++. And if there are still C programmers around I suppose it would be nice in C also. ;)