Reputation: 71
I need to set each bit in 1 byte in Java.
bit7 - 1,
bit6 - 1,
bit5 - 1,
bit4 - 0,
bit3 – 0,
bit2 – 0,
bit1 – 0,
bit0 – 0
I've written:
byte extra_dop = 0b00000111;
but got the following error:
binary literals are not supported in -source 1.5 (use -source 7 or higher to enable binary literals)
Upvotes: 5
Views: 16869
Reputation: 2423
Binary literal were introduced in Java7.
Use following for older version:
byte b = Byte.parseByte("00000111", 2);
Upvotes: 10
Reputation: 206836
As the error message says, the 0b...
syntax did not exist yet in Java 5 (which is what you seem to be using); it was introduced with Java 7. If you are using Java 7, make sure your compiler settings (in your IDE or build file) are set so that it accepts Java 7 syntax.
Bits are normally counted from the right to the left, so if you say bit 7 is 1, bit 6 is 1, etc. then I would expect the binary number to be 11100000
instead of 00000111
.
To write this in source code in a Java version older than Java 7, you could simply write it as a hexadecimal or decimal number:
// Hexadecimal
byte extra_dop = (byte)0xE0; // or did you mean 0x07?
// Decimal
byte extra_dop = (byte)224; // or did you mean 7?
You could also use Integer.parseInt()
with radix 2:
byte extra_dop = (byte)Integer.parseInt("11100000", 2);
(Note, you could also use Byte.parseByte
but it will not accept 11100000
since it exceeds the range of the signed byte
type).
Upvotes: 4
Reputation: 1824
It depends on what you want to accomplish. If you just want to assign a value that won't be binary changed then what you are doing is just fine, but to use that functionallity you will have to compile specifying that javac will receive a source code that complies with java 7 (that is what the error messaging is saying). To do this depends on the way you are compiling, if you are using Netbeans or Eclipse then you will do this on the project properties configuration (just right click on the project and look for the properties, it will open a dialog, I don't remember right now where the source code compatibility is in each IDE, but I am almost sure it is right in the main screen of the dialog).
However if you want to edit the number later using bit operations then you will need to work like @Sean said using BitSet (actually you could also use bit operations directly on the numbers like we do in C/C++, it is just not confortable, but possible).
Upvotes: 0
Reputation: 298908
That's not the way we do things in Java. Have a look at the BitSet
class, it's a much more convenient way of setting bit flags.
Hmpfh. Let me rephrase that. Java is an Object Oriented language where there are efficient and Object Oriented ways of doing things in a more developer-friendly way than with bit operators. I'd suggest you use BitSet
, as it makes your code much more readable, and it can support many more flags than a simple bit mask. Better?
Upvotes: 0