How to get 0-padded binary representation of an integer in java?

前端 未结 17 2332
我在风中等你
我在风中等你 2020-11-22 08:23

for example, for 1, 2, 128, 256 the output can be (16 digits):

0000000000000001
0000000000000010
0000000010000000
0000000100000000
17条回答
  •  北荒
    北荒 (楼主)
    2020-11-22 08:47

    import java.util.Scanner;
    public class Q3{
      public static void main(String[] args) {
        Scanner scn=new Scanner(System.in);
        System.out.println("Enter a number:");
        int num=scn.nextInt();
        int numB=Integer.parseInt(Integer.toBinaryString(num));
        String strB=String.format("%08d",numB);//makes a 8 character code
        if(num>=1 && num<=255){
         System.out.println(strB);
        }else{
            System.out.println("Number should be in range between 1 and 255");
        }
      }
    }
    

提交回复
热议问题