Home > Enterprise >  How would I format my binary in 4 bit groups after my binary conversion program in Java?
How would I format my binary in 4 bit groups after my binary conversion program in Java?

Time:05-17

import java.util.*;

public class Binary {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Scanner input = new Scanner(System.in);

        int number = input.nextInt();
        String binary = Integer.toBinaryString(number);
        System.out.println(binary);

    }

}

I am trying to create a program which converts an integer into binary and groups every four bits. For example, if I input 1, I want to get 0001, but I get 1

CodePudding user response:

Take the number 4 bits at a time, and print the bits.

Use a recursive implementation to get the nibbles printed in the correct order.

public static void main(String[] args) {
   Scanner input = new Scanner(System.in);
   printbin(input.nextInt());
}

static void printbin(int number) {
    int lo = number & 15;
    int hi = number >>> 4;
    if (hi != 0) {
        printbin(hi);
        System.out.print('.');
    }
    for (int n=3; n>=0; n--) {
        System.out.print((lo >> n) & 1);
    }
}

Given 291 (which is 0x123) the output is
0001.0010.0011

CodePudding user response:

You can make your own toBinaryString method. But first you have to understand the << operator, it basically shifts binary numbers to the left by the value you give to it. example:

int n = 1; // 0001
n = ( n<<(4-1) ); // shift the binary number of 1 to the left 3 times
System.out.println(toBinaryString(n)); // = 1000;

now you might ask what is the usage of this? well you can make your own toBinaryString method with the help of the shift operator to do what you want

but before jumping to the code you have to know how the & operator works: 1000 & 0001 = 0

public static String toBinaryString(int n) {
    String binary = ""; //Start with an empty String

    // int i in binary = 1000, as long as i > 0, divide by 2
    for (int i = (1 << (4 - 1)); i > 0; i /= 2) {

        // if binary n & i are NOT 0, add 1 to the String binary, Otherwise add 0
        binary  = (n & i) != 0 ? "1" : "0";
    }
    return binary;
}

let's say you put 1 as input:

toBinaryString(1); // 1 = 0001 in binary

the function starts:

i starts at a binary value of 1000 which is equal to int 8 is 8 bigger than 0? yes, divide by 2 8/2 = 4; 4 in binary is 00100, now lets compare it with our input 0001

00100 & 0001 = 0? // YES

add 0 to String binary.

now divide 4 by 2 and repeat the loop. The function will add 3 zeros and 1 at the end. That will be your 0001.

At the end of the loop binary will be your wanted value as a String.

I hope i helped

~Mostafa

CodePudding user response:

Let's throw some Streams, Collectors and RegEx into our solution to complete the learning exercise.

Stream / Collector / RegEx solution:

import java.util.Arrays;
import java.util.Scanner;
import java.util.stream.Collectors;

class Binary
{
  public static void main( String[] args )
  {
    Scanner input = new Scanner( System.in );
    int number = input.nextInt();
    String binary = Integer.toBinaryString( number );
    System.out.println( binary );

    // SOLUTION:
    int digitsInGroup = 4;
    String separator = ".";
    while( binary.length() % digitsInGroup > 0 )
      binary = "0"   binary;
    binary = Arrays.stream( binary.split( String.format( "(?<=\\G.{%d})", digitsInGroup ) ) ).collect( Collectors.joining( separator ) );
    System.out.println( binary );
  }
}

Output:

> java Binary.java
1
1
0001

> java Binary.java
16
10000
0001.0000

> java Binary.java
31000
111100100011000
0111.1001.0001.1000

CodePudding user response:

Primitive approach:

import java.util.*;
public class Binary {
    public static void main(String[] args) {
        try (Scanner input = new Scanner(System.in)) {
            int number = input.nextInt();
            String binary = Integer.toBinaryString(number);
            System.out.println(binary);

            int paddingLength = (4 - binary.length() % 4) % 4;
            StringBuilder grouped = new StringBuilder();
            for (int i = 0; i < paddingLength; i  ) {
                grouped.append('0');
            }
            for (int i = 0; i < binary.length(); i  ) {
                if (i != 0 && (i   paddingLength) % 4 == 0) {
                    grouped.append('.');
                }
                grouped.append(binary.charAt(i));
            }
            System.out.println(grouped);
        }
    }
}
$ java Binary.java
1
1
0001
$ java Binary.java
16
10000
0001.0000
$ 
  • Related