In Java, can I define an integer constant in binary format?
So, with the release of Java SE 7, binary notation comes standard out of the box. The syntax is quite straight forward and obvious if you have a decent understanding of binary:
byte fourTimesThree = 0b1100;
byte data = 0b0000110011;
short number = 0b111111111111111;
int overflow = 0b10101010101010101010101010101011;
long bow = 0b101010101010101010101010101010111L;
And specifically on the point of declaring class level variables as binaries, there's absolutely no problem initializing a static variable using binary notation either:
public static final int thingy = 0b0101;
Just be careful not to overflow the numbers with too much data, or else you'll get a compiler error:
byte data = 0b1100110011; // Type mismatch: cannot convert from int to byte
Now, if you really want to get fancy, you can combine that other neat new feature in Java 7 known as numeric literals with underscores. Take a look at these fancy examples of binary notation with literal underscores:
int overflow = 0b1010_1010_1010_1010_1010_1010_1010_1011;
long bow = 0b1__01010101__01010101__01010101__01010111L;
Now isn't that nice and clean, not to mention highly readable?
I pulled these code snippets from a little article I wrote about the topic over at TheServerSide. Feel free to check it out for more details:
Java 7 and Binary Notation: Mastering the OCP Java Programmer (OCPJP) Exam
Declaring a binary integer constant
If you are using Java 7 or higher, you can specify binary constants by prepending "0b" to your value, e.g.:
long value = 0b000100110011010001010111011110011001101110111100110111111110001L;
If that language feature is not available to you, you can use decimal, octal, or hexadecimal notation, however. If you're just declaring constants, you can use an online tool such as http://www.mathsisfun.com/binary-decimal-hexadecimal-converter.html, or perhaps your favorite calculator, to convert to a radix that Java recognizes.
For example:
long value = 691913582662545393L;
Or:
long value = 0x99A2BBCCDDE6FF1L;
You may want to clarify by describing what that value means in a comment:
// binary: 000100110011010001010111011110011001101110111100110111111110001
long value = 0x99A2BBCCDDE6FF1L;
As you may have noticed from the above examples, you will need to use a long
and add the L
suffix to your constant. In Java, int
is 32-bit and long
is 64-bit. The L
suffix specifies a long
literal, without it, it is an int
and the value would be too large.
P.S. Integer literals starting with "0" (but not "0x" or "0b") are interpreted as octal. The constant you originally attempted to specify was interpreted as a very large octal number.
How to write something in binary and assign it to a variable?
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);
Are there binary literals in Java?
Starting with Java 7 you can represent integer numbers directly as binary numbers, using the form 0b
(or 0B
) followed by one or more binary digits (0 or 1). For example, 0b101010
is the integer 42. Like octal and hex numbers, binary literals may represent negative numbers.
If you do not have Java 7 use this:
int val = Integer.parseInt("001101", 2);
There are other ways to enter integer numbers:
As decimal numbers such as
1995
,51966
. Negative decimal numbers such as-42
are actually expressions consisting of the integer literal with the unary negation operation.As octal numbers, using a leading 0 (zero) digit and one or more additional octal digits (digits between 0 and 7), such as 077. Octal numbers may evaluate to negative numbers; for example
037777777770
is actually the decimal value -8.As hexadecimal numbers, using the form 0x (or 0X) followed by one or more hexadecimal digits (digits from 0 to 9, a to f or A to F). For example,
0xCAFEBABEL
is the long integer 3405691582. Like octal numbers, hexadecimal literals may represent negative numbers.
More details can be found in this Wikibook.
What does a number like this mean in Java: 0b1000_1100_1010? (The b between the numbers)
This is the binary literal.
It's a notation to show that the number is represented in binary.
It's like when you use the hexadecimal notation: 0xF9
. In Java, you can use 0b1111_1001
to represent the same number, which is 249 in decimal.
It's not related to bytes, but to bits. You can clearly see which bits are set and which are not. By default a number starting with 0b
is an int
, but you can write a long like this 0b1010L
(note the trailing L
).
The b
can be lowercase or uppercase. So this is also valid: 0B1111
. Note that since the 0b
prefix indicates a binary representation, you're not allowed to use any character other than 0
and 1
(and _
to mark a separation).
storing charcter and binary number in a hash map
You just can't store them with leading zero. Leading zero to an integer indicates that it's an octal number.
Since your next step is XOR, I recommend this approach.
- You can store these integers using simple base 10 numbers. We will convert them when needed as binary. (you can also store them simply as binary with leading
0b
. See this answer for more details. - Use
Integer.toString(hm.get(s), 2);
to display binary number. The original number is still an Integer so you can use it for XOR operation. For displaying binary with leading zero, I've played with some string methods like this:
String temp = "000", binary;
for( String s : input ) {
binary = Integer.toString(hm.get(s), 2);
System.out.print(temp.substring(0, 3-binary.length()) + binary +" ");
}
Here's what the final code looks like:
Output
Binary form of text is ....
001 000 010 100 001 010 111 100 000 101
Code
import java.util.*;
public class onetimepad {
public static void main(String args[]) {
HashMap <String , Integer>hm = new HashMap <String , Integer> ();
hm.put("e", 0); //or use hm.put("e", 0b000);
hm.put("h", 1); //or use hm.put("e", 0b001);
hm.put("i", 2);
hm.put("k", 3);
hm.put("l", 4);
hm.put("r", 5);
hm.put("s", 6);
hm.put("t", 7);
String[] key = { "t" ,"r" , "s" , "r","t","l","e", "r","s","e"};
//key = t r s r t l e r s e
String[] input = {"h","e","i" ,"l","h","i","t","l","e","r"};
int[] cipher = new int[10];
System.out.println("Binary form of text is ....");
String temp = "000", binary;
for( String s : input ) {
binary = Integer.toString(hm.get(s), 2);
System.out.print(temp.substring(0, 3-binary.length()) + binary +" ");
}
}
}
Binary literals?
I'd use a bit shift operator:
const int has_nukes = 1<<0;
const int has_bio_weapons = 1<<1;
const int has_chem_weapons = 1<<2;
// ...
int dangerous_mask = has_nukes | has_bio_weapons | has_chem_weapons;
bool is_dangerous = (country->flags & dangerous_mask) == dangerous_mask;
It is even better than flood of 0's.
(Java) Specify number of bits (length) when converting binary number to string?
Use Integer.toBinaryString()
then check the string length and prepend it with as many zeros as you need to make your desired length.
Related Topics
Why Shouldn't Java Enum Literals Be Able to Have Generic Type Parameters
Why Is This Java Code in Curly Braces ({}) Outside of a Method
Invalid Syntax Error "Type= Myisam" in Ddl Generated by Hibernate
What to Return If Spring MVC Controller Method Doesn't Return Value
Collection Interface VS Arrays
Write a File in Utf-8 Using Filewriter (Java)
Determine Whether Daylight Savings Time (Dst) Is Active in Java for a Specified Date
Eclipse Will Not Open Due to Environment Variables
What Is the Most Recommended Way to Store Time in Postgresql Using Java
How to Read a Text-File Resource into Java Unit Test
Export PDF Pages to a Series of Images in Java
How to Use Readline() Method in Java
Qr Code Encoding and Decoding Using Zxing
How to Load an Org.W3C.Dom.Document from Xml in a String