【问题标题】:Convert integer to integer array or binary将整数转换为整数数组或二进制
【发布时间】:2013-09-09 21:51:26
【问题描述】:

我正在尝试使用整数数组将整数转换为二进制数。第一个转换是 toBinaryString,我得到正确的转换“11111111”,然后下一步转换为数组。这是出错的地方,我认为它是 getChar 行。

int x = 255;

string=(Integer.toBinaryString(x));

int[] array = new int[string.length()];

for (int i=0; i< string.length(); i++){
array[i] = string.getChar(i);

   Log.d("TAG", " Data " + array[1] "," + array[2] + "," + array[3]);

日志显示(Data 0,0,0)我要找的结果是(Data 1,1,1)

这是最终代码,它可以工作。

        // NEW
int x = 128;

string=(Integer.toBinaryString(x));

int[] array = new int[string.length()];

for (int i=0; i < string.length(); i++) {
array[i] = Integer.parseInt(string.substring(i,i+1));
}

Log.d("TAG", "Data   " + array[0] + "" + array[1]+ "" + array[2] + "" + array[3]+  " " + array[4]+ "" + array[5] + "" + array[6] + "" + array[7]);

【问题讨论】:

  • 你怎么称呼String.getChar(),看不到它可用。我想知道您的应用程序在执行array[3] 时如何没有崩溃,因为我看到索引为 [0,1&2]
  • 没有String.getChar(int) 方法。你的意思是String.charAt(int index)?尝试发布代码编译
  • 代码确实编译但我有 array[i] = string.getChar(i);因为有错误所以注释掉了。数组应为 0 到 7,因此日志不应使数组 [3] 崩溃。 Mattias,我得到一个类型不匹配:无法从 Integer[] 转换为 int[] on int digits[] = new Integer[Integer.SIZE];
  • 谢谢大家,我使用了你们每个想法中的代码并让它发挥作用。再次感谢你..

标签: java android arrays


【解决方案1】:

首先,数组是从索引0而不是1开始的,所以改成下面这行代码:

Log.d("TAG", " Data " + array[1] "," + array[2] + "," + array[3]);

收件人:

Log.d("TAG", " Data " + array[0] "," + array[1] + "," + array[2]);

接下来,以下代码行:

array[i] = string.getChar(i);

您正在尝试将字符值获取到 Integer 数组,您可能想尝试以下操作并将值解析为 Integer(此外,“getChar”函数不存在):

array[i] = Integer.parseInt(String.valueOf(string.charAt(i)));

希望我能帮上忙。

P.S - 感谢 Hyrum Hammon 指出 String.valueOf。

【讨论】:

  • 我很确定那一定是Integer.parseInt(String.valueOf(string.charAt(i)));
  • 不确定getCharString 上没有这种方法。此外,Integer.parseInt 有一个小写的“p”(符合 Java 命名约定)。
  • 嗯,好像没有parseInt(char),所以会抛出编译错误。你可以先把它变成一个字符串,但Character.digit(string.charAt(i), 2) 可能更快更直接。
  • 是的,刚刚检查过。你确实需要 String.valueOf
【解决方案2】:

怎么样:

array[i] = Integer.parseInt(string.substring(i,i+1));

【讨论】:

    【解决方案3】:
    // Take your input integer
    int x = 255;
    // make an array of integers the size of Integers (in bits)
    int[] digits = new Integer[Integer.SIZE];
    // Iterate SIZE times through that array
    for (int j = 0; j < Integer.SIZE; ++j) {
      // mask of the lowest bit and assign it to the next-to-last
      // Don't forget to subtract one to get indicies 0..(SIZE-1)
      digits[Integer.SIZE-j-1] = x & 0x1;
      // Shift off that bit moving the next bit into place
      x >>= 1;
    }
    

    【讨论】:

    • 我在想类似的东西,只是使用boolean[] 来表示位数组并使用this question 的答案之一。但是,OP 不清楚生成的应该数组是否应该具有最小大小(array[0] 始终为 1,除非x == 0)或固定大小(array.length == Integer.SIZE(即 32))。
    • 我知道数组从 0 开始,但我只对 1、2、3 感兴趣,以供日志参考。关于原因的任何想法:int digits[] = new Integer[Integer.SIZE];给出了错误。
    猜你喜欢
    • 1970-01-01
    • 2017-08-21
    • 2012-04-10
    • 2019-03-29
    • 2020-12-05
    • 1970-01-01
    • 1970-01-01
    • 2016-07-08
    • 1970-01-01
    相关资源
    最近更新 更多