简体   繁体   English

我想将数字拆分为一个数字并将其更改为android中的二进制

[英]I want to split a number into single digit and change it into the binary in android

I have a number 83 I want to split this number like 8 and 3 then want to change the number into binary form in android and want the result.how can I do this.Please help me 我有一个数字83我想将此数字拆分为8和3,然后在android中将该数字更改为二进制形式并想要result。我该怎么做。请帮助我

Thanks 谢谢

You can convert an integer value to binaryString using Integer.toBinaryString(int) . 您可以使用Integer.toBinaryString(int)integer数值转换为binaryString

Now, to split your integer into individual digits, you can use simple mathematics using modulus (%) and division (/) operators. 现在,要将整数拆分为单个数字,您可以使用使用modulus (%)division (/)运算符的简单数学。

Here's the recursive function that you can use: - 这是您可以使用的递归函数:-

public static void convert(int num) {

    if (num > 0) {
        int lastDigit = num % 10;
        convert(num / 10);
        System.out.print(Integer.toBinaryString(lastDigit) + " ");
    }
}

// From your main method
convert(83);

OUTPUT: - 输出:-

1000 11

To Get Digits from a number use following method: 要从数字获取数字,请使用以下方法:

String str = String.valueOf(someInt);

char[] digits = str.toCharArray();

now itereate through digits array. 现在通过数字数组进行迭代。 and convert each digit to binary, by 并将每个数字转换为二进制

Integer.toBinaryString(Character.digit(digits[i], 10));
 public String conIntTOBin(String num) {
        String temp = "";

        for(int i=0; i < num.length(); i++) {                               
              temp += Integer.toBinaryString(Integer.parseInt(""+num.charAt(i)));
        }
        return temp;

 }

pass your integer number as a string perametre. 将整数作为字符串perametre传递。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM