-2

I have an int array int[] stegoBitsArray = {0,1,1,0,1,1,0,0,0,1,1,0,0,0,0,1...} I want each 8 bits converted to byte and added to byte array which i would later convert to char array because 01101100 is letter "l" and so on so ... So i tried using ByteBuffer but it throws me BufferOverflowException here's my code snippet:

 int[] stegoBitsArray = getStegoTextFromImage(stegoImage);
 ByteBuffer byteBuffer = ByteBuffer.allocate(stegoBitsArray.length);
 for (int i = 0; i < stegoBitsArray.length; i++) {
    byteBuffer.putInt(stegoBitsArray[i]);
 }

Or it's more better to convert from int array to characters?

  • 2
    Is `0110110001100001` a **decimal number** that only contains 0/1 digits, or is it a **binary number** you wrote binary? – Willem Van Onsem Apr 01 '17 at 19:10
  • It's an array which contains value 0 or 1 – Klausimelis Jonas Apr 01 '17 at 19:16
  • If you want to convert 8 `int` values of `0` or `1` to a `byte`, then *you* have to do that using bit-manipulation, e.g. using the `<<` and `|` operators. There is no library method to do that for you, *you* have to write the code to do it. --- *Opinion:* What kind of idiotic method is `getStegoTextFromImage()`, returning *bits* as an `int[]`? *Yikes!* – Andreas Apr 01 '17 at 19:17
  • http://stackoverflow.com/questions/1086054/how-to-convert-int-to-byte – Cardinal System Apr 01 '17 at 19:21
  • How to convert 01101100 to it's decimal value 108 using bit manipulation ? – Klausimelis Jonas Apr 01 '17 at 19:29

2 Answers2

1

To convert from binary to char you have to convert each 8 bit binary into byte and then you can cast from byte to char. Example:

byte b = Byte.parseByte("01100001", 2);
        System.out.println((char)b);

Prints

a
Jay Smith
  • 2,331
  • 3
  • 16
  • 27
0

How come you can have a value like 0110110001100001 in an integer array. Either it can be stored as a string or there is another way.

You can have an array of integer values something like int array = {123, 456, 333} etc then you can directly convert those integers to characters by looping on the array.

for(int i = 0; i < array.length; i++){
   char c = (char)array[i];  
   System.out.println(c);
}

Or if you want to convert integer to binary then Java supports in Integer class a method called toBinaryString. you can find a good resource for it HERE.

The combination of these two can lead you to your desired solution.

Anant666
  • 416
  • 9
  • 26