3

Possible Duplicate:
In Java, can I define an integer constant in binary format?

In python, you can do something like:

a = 0b00000010 which would set a to 2.

Is it possible to do something like that in Java? I know I could just go through and assign my varibles by the number instead of binary, but I like the visual.

Thanks ~Aedon

Community
  • 1
  • 1
ahodder
  • 11,353
  • 14
  • 71
  • 114
  • You can do the same thing in java 7 `a = 0b00000010` – Eng.Fouad Jul 21 '11 at 17:00
  • 1
    this is a dup question. answered here: http://stackoverflow.com/questions/867365/in-java-can-i-define-an-integer-constant-in-binary-format – alphazero Jul 21 '11 at 17:00
  • 2
    You could wait for Java7, that supports binary literals (for some inexplicable reason) – skaffman Jul 21 '11 at 17:01
  • 2
    @skaffman: It's inexplicable that Java would support binary literals? Is there a more self-documenting way of showing int masks in code? – Mark Peters Jul 21 '11 at 17:02
  • @Mark Peters - Yessir, thats what I am doing now. – ahodder Jul 21 '11 at 17:04
  • @All - Thanks all. I didn't know that Java 7 supported binary literals. Good to know, but I am working with android, which as far as I know isn't getting Java 7 for a while. Looks like I'm stuck with just using straight numbers. – ahodder Jul 21 '11 at 17:07
  • what's wrong with hex `0x02`? – ratchet freak Jul 21 '11 at 17:13
  • 1
    @ratchet freak - Nothing is wrong with it. But I am doing bitmask flags and wanted to visualize how the flags were laid out. Preference is in question here not functionality. – ahodder Jul 21 '11 at 17:18
  • @ratchet: Hex can be really hard to visualize sometimes. I've worked with protocols that stuff a field into an int from bits 2 to 7 for example. If the bits you care about aren't aligned with a nybble it gets really messy in hex. – Mark Peters Jul 21 '11 at 21:08

1 Answers1

9

In Java 7, you can do

int a = 0b00000010;

However if you're working with an older version, I'm afraid you're stuck with

int a = Integer.parseInt("00000010", 2);
tskuzzy
  • 35,812
  • 14
  • 73
  • 140