0

I'm trying to give an array of string a binary value for example.

 String list_command[]= {"movie", "audio", "games", "current_time", "city", "city"};

would be something like

list_command = 000,001,010,011,100,101
Never_Nude
  • 27
  • 5
  • you want someone to code ? – Kick Jan 27 '14 at 19:09
  • 2
    Do you just want the array indices in binary, or are you looking to transform the value into some binary value? – AntonH Jan 27 '14 at 19:09
  • There is no such thing as a "binary value". If you have an integer value, you can write it down as a binary *number*, or a decimal *number*, and so on. And your example doesn't give "an array a (binary) value", it associates strings with values you chose to denote (for whatever reason) as binary numbers. – laune Jan 27 '14 at 19:20

2 Answers2

0

You could try using a Dictionary. I'm not sure what you would want for your keys/values, but if you wanted to look-up by strings you have in list_command[] you could try something like this:

Dictionary<string, string> commandsToBinary = new Dictionary<string,string>();

for(int i = 0; i < list_command.Length; i++){
    string binaryCommand = Convert.ToString(i,2); // Get the binary representation of `i` as a string.
    commandsToBinary.Add(command, binaryCommand); //switch command & binaryCommand to have the binary strings as your keys.
}
Nate Jenson
  • 2,664
  • 1
  • 25
  • 34
0

Build Binary Array

public static byte[][] toBinary(String... strs) {
    byte[][] value = new byte[strs.length][];

    for(int i=0; i<strs.length; i++) {
        value[i] = strs[i].getBytes();
    }

    return value;
}

Build String Array

public static String[] toStrings(byte[][] bytes) {
    String[] value = new String[bytes.length];

    for(int i=0; i<bytes.length; i++) {
        value[i] = new String(bytes[i]);
    }

    return value;
}

Print Values: source (Convert A String (like testing123) To Binary In Java)

public static void print(byte[][] bytes) {
    for(byte[] bArray : bytes) {
        StringBuilder binary = new StringBuilder();

        for (byte b : bArray)
          {
             int val = b;
             for (int i = 0; i < 8; i++)
             {
                binary.append((val & 128) == 0 ? 0 : 1);
                val <<= 1;
             }
             binary.append(' ');
          }

        System.out.println(binary.toString());
    }
}

Main

public static void main(String... args) {
    print(toBinary("Hello", "World"));
}
Community
  • 1
  • 1
Isaiah van der Elst
  • 1,435
  • 9
  • 14