Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert bitstring to byte in java

Tags:

java

byte

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)

like image 578
user2656572 Avatar asked Dec 11 '13 10:12

user2656572


People also ask

Can we convert long to byte in Java?

Long class has the following methods for converting long type value to other primitive types. byte byteValue() returns the value of this Long as a byte. double doubleValue() returns the value of this Long as a double.

Can we convert string to byte array in Java?

We can use String class getBytes() method to encode the string into a sequence of bytes using the platform's default charset. This method is overloaded and we can also pass Charset as argument. Here is a simple program showing how to convert String to byte array in java.

Can we convert double to byte in Java?

Double is a higher datatype compared to byte. Therefore, double value will not be converted into byte implicitly, you need to convert it using the cast operator.

Can Char be converted to byte?

We can typecast the char variable into its equivalent Byte value by using explicit type-casting.


1 Answers

Binary literal were introduced in Java7.

Use following for older version:

byte b = Byte.parseByte("00000111", 2);
like image 182
Amit G Avatar answered Sep 24 '22 01:09

Amit G