2

I have a integer list which contains some binary values

List<Integer> binary = new ArrayList();
for (int i=0; i<8; i++)
{
    bin[i] = pText[i] ^ ivKey[i]; //some binary value is calculated
    binary.add(bin[i]); //the binary list gets updated here
}

for (int i=0; i<myCipher2.size(); i++)
{
    System.out.print(binary.get(i)); //this prints the appended binary as shown in the output
}

The list when printed gives the following:

000001010100001110011101

Each 8 bits refers to a hex so the output I want when converted should give me the following

05 43 9d

How can I break the list into 8 bits and convert those 8 bits into hex?

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
vbenthu
  • 37
  • 7

3 Answers3

2

You can create a binary string and convert it to decimal and then to hex:

    int[] arr = {0,0,0,0,0,1,0,1,0,1,0,0,0,0,1,1,1,0,0,1,1,1,0,1};
    int i = 0;
    while (i < arr.length) {
        String res = "";
        for(int j = 0; j < 8; j++) {
            res += arr[i];
            i++;
        }
        System.out.println(Integer.toHexString(Integer.parseInt(res, 2)));
    }

OUTPUT

5
43
9d
Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129
1

First things first, you should not declare generic objects with raw types, add a type to your ArrayList:

List<Integer> binary = new ArrayList<Integer>();

Since it isn't directly related to your question, you can read why you should do this here

Now, so since your list holds individual binary digits, what you can do is use a StringBuilder to build 8-bit binary strings from it. You can also use a StringBuilder to build the converted hex value. Each time you build this 8-bit string, you convert it to it to hex (actually first to decimal and then to hex) and append it to the StringBuilder then builds the hex string.

Here is the code:

// ... your program

StringBuilder hexString = new StringBuilder();
StringBuilder eightBits = new StringBuilder();
for(int i = 0; i < binary.size(); i += 8) {                 
    for(int j = i; j < (i + 8) && j < binary.size(); j++) { // read next 8 bits or whatever bits are remaining
        eightBits.append(binary.get(j)); // build 8 bit value
    }
    int decimal = Integer.parseInt(eightBits.toString(), 2); // get decimal value
    hexString.append(Integer.toHexString(decimal) + " "); // add hex value to the hex string and a space for readability 
    eightBits.setLength(0); // reset so we can append the new 8 bits
}
System.out.println(hexString.toString()); // prints "5 43 9d" for the value you gave

Note: this program is a continuation of your program

Community
  • 1
  • 1
nem035
  • 34,790
  • 6
  • 87
  • 99
  • the whole issue is how to read 8 characters at time from the list or String? – Kick Buttowski Sep 24 '14 at 03:39
  • 1
    @KickButtowski Yes, that is the main issue here – vbenthu Sep 24 '14 at 03:41
  • @KickButtowski well, I just tried to answer his question, not completely redo his program. I edited again to fit his code and the program does what he needs. Hopefully, this is to everybody's satisfaction :) – nem035 Sep 24 '14 at 04:26
  • @nem so many times, I get voted down because I represent no optimized solutions, and their justification was since the op did not said what way, you MUST represent the best way you can. I did not vote you down as you see, yet it is logical to ask why we should learn this when even you claim it is not a right and good way? – Kick Buttowski Sep 24 '14 at 04:28
  • @KickButtowski i completely understand and agree with you. However, **vbenthu** is just messing around and learning, his whole approach seems very efficient, but he didn't show his full code for me to determine how to optimize it nor he asked advice on how to do that. I specifically targeted to answer his direct question which is how to convert 8 individual binary digits from a list into a hex value. Do you think I shouldn't do this and delete my answer? There can be a whole discussion made on whats and hows to approach solving this problem, I just wanted to help him solve it his way... – nem035 Sep 24 '14 at 04:34
  • @nem thank you nem for your effort, time and explanation. Your code works just fine. Really appreciate. – vbenthu Sep 24 '14 at 04:36
1

So, here's my take on it...

Basically, this uses List#subList to create a sub list of the main binary array. Each sublist contains up to 8 values...

int length = Math.min(8, bits.size());
List<Integer> byteList = bits.subList(0, length);

I then reverse this list, you easily reverse the for-loop order, this just seem simpler to me...

Collections.reverse(byteList);

Then I use a simple for-loop to loop through the sub list. For each bit that is 1, I simply add it's binary equivalent (Math.pow(2, index)) to the resulting value

for (int index = 0; index < byteList.size(); index++) {
    int bit = byteList.get(index);
    if (bit == 1) {
        int pos = (int)Math.pow(2, index);
        value += pos;
    }
}

Then I remove the first n values the master list and continue until there is nothing left...

This will then print...

Word = 00000101 = 5; 0x05
Word = 01000011 = 67; 0x43
Word = 10011101 = 157; 0x9d

Runnable example...

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Test100 {

    public static void main(String[] args) {
        List<Integer> bits = new ArrayList<Integer>(25);
        bits.add(0);
        bits.add(0);
        bits.add(0);
        bits.add(0);
        bits.add(0);
        bits.add(1);
        bits.add(0);
        bits.add(1);

        bits.add(0);
        bits.add(1);
        bits.add(0);
        bits.add(0);
        bits.add(0);
        bits.add(0);
        bits.add(1);
        bits.add(1);

        bits.add(1);
        bits.add(0);
        bits.add(0);
        bits.add(1);
        bits.add(1);
        bits.add(1);
        bits.add(0);
        bits.add(1);

        System.out.println();

        while (bits.size() > 0) {

            int length = Math.min(8, bits.size());
            List<Integer> byteList = bits.subList(0, length);
            Collections.reverse(byteList);
            int value = 0;
            StringBuilder binary = new StringBuilder(8);
            for (int index = 0; index < byteList.size(); index++) {
                int bit = byteList.get(index);
                if (bit == 1) {
                    int pos = (int)Math.pow(2, index);
                    value += pos;
                }
                binary.insert(0, bit);
            }

            System.out.println("Word = " + binary + " = " + value + "; 0x" + pad(2, Integer.toHexString(value)));

            int size = Math.max(0, bits.size());
            bits = bits.subList(length, size);

        }
    }

    public static String pad(int length, String value) {
        StringBuilder zeros = new StringBuilder(value);
        while (zeros.length() < length) {
            zeros.insert(0, "0");
        }
        return zeros.toString();
    }

}
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • 1
    @KickButtowski Don't know if it's any better or worse than the other approaches, was hoping to do some bit masking, but that was proving to implode my head...ah, takes me back to my days at high school...:P – MadProgrammer Sep 24 '14 at 05:58
  • u r a hoot sir. I'll study ur way for sure . alsafin gave the good answer too. thank u again – Kick Buttowski Sep 24 '14 at 06:00