-1

I am working with an array of 8 bits and I am trying to convert it to a single char in Java. I am trying to do something along the lines of

byte[] bytes2 = {0,0,0,0,0,0,0,0};
        char c = (char) bytes2);

It is throwing a compilation error that I can not case a byte[] to a char. I have gotten it to compile, but not work correctly by assigning char c to just one of the elements of the array. I am just stuck on this part, and would appreciate a little bit of help.
Thank you

2
  • 3
    First of all byte[] is an array of bytes, not of bits! Commented Jan 26, 2019 at 15:23
  • Possibly related Commented Jan 26, 2019 at 15:27

2 Answers 2

3

byte[] is array of bytes, and 1 byte is 8 bit, 1 char is also 8 bit.

You initiate byte[] with {0,0,0,0,0,0,0,0}; It means your store 8 * 8 = 64 bits in bytes2 variable.

So you can't store 64 bits data into single char (8 bit).

But you can do this:

byte[] bytes2 = {0,0,0,0,0,0,0,0};
char c = (char) bytes2[0]; // store first element (8 bit) into single char (1 bit) and cast it.
Sign up to request clarification or add additional context in comments.

Comments

1

You can't convert it to a one single char. Instead of that you can convert it to a single String and then convert that to a char array like below,

    byte[] bits2 = {0, 0, 0, 0, 0, 0, 0, 0};
    String value = new String(bits2);
    char[] chars = value.toCharArray();

Comments

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.