给一个字符串数组一个二进制值

时间:2014-01-27 19:07:40

标签: java

我试图给一个字符串数组一个二进制值例如。

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

会像

list_command = 000,001,010,011,100,101

2 个答案:

答案 0 :(得分:0)

您可以尝试使用Dictionary。我不确定您对键/值的要求是什么,但如果您想在list_command[]中查找字符串,可以尝试这样的事情:

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.
}

答案 1 :(得分:0)

构建二进制数组

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;
}

构建字符串数组

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;
}

打印值:来源(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());
    }
}

主要

public static void main(String... args) {
    print(toBinary("Hello", "World"));
}
相关问题