2

There is a binary String :

String binaryString = "101101010111001011111000";

This string is of length 24, so it can be converted into 3 bytes.

The number that byte can contain is -128 to 127 but in the raw format it contains 8 bits.

Say : binary1 is 10110101 and binary2 is 01110010 and binary3 is 11111000

I want to convert this binaryString into raw bytes but when I am trying

Byte.parseByte(binary1,2);

But this method convert using int and the limit of byte ranges applies.

I want to write this binaryString to the file in form of byte.

What can be the solution to have the raw byte containing 8 bits and nothing treated like number or int ?

3
  • Figure out how to use shift/mask operations to extract the individual bytes from an int. It's not hard or particularly esoteric. (I suspect that this is the goal of this little exercise, so you might as well do it.) Commented Jan 22, 2014 at 16:50
  • 1
    @HotLicks Unfortunately, as in a few other questions today, people dealing with bytes, byte arrays and the like often seem to have not the slightest idea about very basic concepts, such as binary data representation. Amazing. Commented Jan 22, 2014 at 16:57
  • @Ingo - Yep, even though this sort of knowledge is fundamental to programming. I don't know if it's just that instructors don't spend enough time on it, or if students blow it off. Commented Jan 22, 2014 at 17:01

1 Answer 1

2

The following should work:

byte theByte = (byte) Integer.parseInt("10101010", 2);

The parsed string must not be longer than 8, otherwise only the right-most 8 bits will be in the variable theByte.

Please make sure to check your output with appropriate tools (no text editors!).

Sign up to request clarification or add additional context in comments.

5 Comments

I guess it will cause the data loss ? pareByte also internally do the same time. I don't want to play with numbers, I just want the raw data of bits.
As byte allow only -128 to 127 but number of bits allowed is 8. pareByte also internally do the same time. I don't want to play with numbers, I just want the raw data of bits
@Gaurav No. It's the other way around: Because the number of bits in a byte is only 8, it allows only 256 different numbers. usually it is assumed this are the numbers -128 to 127, inclusive. But since you don't want numbers (as you said), it doesnt matter.
@Gaurav No, it is not the same as Byte.parseByte. For example, it accepts the value above, which parsebyte does not.
Best solution I found to work with signed numbers in java.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.