0

I want to write a function to convert a number to 8 bit binary String. For example: with 20, the result I got is 10100, the expected result I want is 00010100.

public static int printBinaryform(int number) {
    int remainder;

    if (number <= 1) {
        System.out.print(number);
        return 0;
    }

    remainder = number % 2;
    printBinaryform(number >> 1);
    System.out.print(remainder);

    return remainder;
}

public static int encryptionNumber(int number, int key) {
    int encrrptionNumber = number ^ key;
    return encrrptionNumber;
}

with input is 20, I expect the output of 00010100, the actual result is 10100.

schtever
  • 3,210
  • 16
  • 25

1 Answers1

1

You can format the integer 20 as 00010100 using this oneliner:

System.out.println(String.format("%08d", Integer.parseInt(Integer.toString(20, 2), 10)));

I'm not sure this is what you are looking for. Anyways, here's how it works:

String str = Integer.toString(20, 2); // Turn an integer into a string consisting of numbers using base 2 (ie a string of 0:s and 1:s)

int i = Integer.parseInt(str, 10); // Parse the string assuming it is a decimal value

String.format("%08d", i); // Format the integer as a string with length 8 and leading 0:s
Stefan
  • 2,395
  • 4
  • 15
  • 32
  • I can not use this function of Java. I have to write my own function, anyway, that is my homework: The XOR-"encryption" of that number with a specified key. All numbers in the range will be encrypted using the same key. All encryptable numbers must be 32 bit wide, the key must be exactly 8 bit wide. The four bytes of the number are then individually encrypted using the key. – Nguyen Ngoc Hai May 03 '19 at 12:09