Tricker Macedonia
Tricker Macedonia

Reputation: 165

Getting a byte out of a given String of 1s and 0s

I am looking for a fast way to get a byte out of a String, if the string consists of 1s and 0s. For example: String a="101010" . How do I get the Byte b ="101010"?

I looked at some other posts but they usually consist of how to get the byte value of a String. I am interested in basically switching the format.

Edit:
to make it more clear, I am looking for this

String a = "101010"
byte b = //What to do?
System.out.print(b)

--> 0b101010

Upvotes: 0

Views: 143

Answers (2)

Elliott Frisch
Elliott Frisch

Reputation: 201447

A byte is a signed primitive value in Java, when you print it you will get a decimal representation of that value (by default). You need to perform two steps; first, parse the String into a byte; second, display the byte with your desired formatting (as a binary String with leading 0b). That can be done simply enough, something like

String a = "101010";
byte b = Byte.parseByte(a, 2);
System.out.printf("0b%s%n", Integer.toBinaryString(b));

Which outputs (as requested)

0b101010

Upvotes: 0

erickson
erickson

Reputation: 269697

The Byte class and other integral types like Integer can parse numbers in a range of radices from 2 to 36 (encoded using digits 0-9 and letters A-Z).

String a = "101010";
byte b = Byte.parseByte(a, 2);
String c = Integer.toBinaryString(b & 0xFF);
String d = "0b" + c;

Remember, a Java byte is signed, so we need to mask out any high-order bits that would be introduced when used in a way that promotes the value to a signed int.

Upvotes: 2

Related Questions