简体   繁体   中英

Convert a Hexadecimal Input to a Binary and count all 1s -Java

I need help, this is my assignment. How to count the 1s only in Binary of the given hexadecimal input. It gives me the numbers of how many 1 and 0 in binary.

    package javaapplication3;
import java.util.*;
public class JavaApplication3 {
    public static void main(String[] args) {
         System.out.println("Enter the string you want printed : ");
         Scanner sc = new Scanner(System.in);
         String s = sc.next();
         int duck = 0;
         byte[] bytes = s.getBytes();
         StringBuilder binary = new StringBuilder();
         for (byte b : bytes){
             int val = b;
             for (int i = 0; i < 8; i++){
                 binary.append((val & 128) == 0 ? 0 : 1);
                 val <<= 1;
                if( val != 1) {
                    duck++;
             }
            }
             binary.append(' ');
         }
         System.out.println("'" + s + "' to binary: " + binary);
         System.out.println("Number of bit 1 in string: " + duck); 
}
}

It gives me an output:

Enter the string you want printed : BABEFACE

'BABEFACE' to binary: 01000010 01000001 01000010 01000101 01000110 01000001 01000011 01000101

Number of bit 1 in string: 64

BUILD SUCCESSFUL (total time: 10 seconds)

Ummm

BABEFACE as binary looks like 1011 1010 1011 1110 1111 1010 1100 1110 to me...

and the number of 1s should be 24

the way to go tp solve this could be:

  1. parse the string to hex
  2. convert to bin
  3. count the 1s or 0s

Example:

   public static void main(String[] args) {
    Long l = Long.parseLong("BABEFACE", 16);
    String hexAsBin = Long.toBinaryString(l.longValue());
    System.out.println(hexAsBin);
    System.out.println("Number of 1: " + countChars(hexAsBin, "1"));
    System.out.println("Number of 0: " + countChars(hexAsBin, "0"));
    }

    private static int countChars(String hexAsBin, String x) {
    return hexAsBin.length() - hexAsBin.replace(x, "").length();
    }

To check for all "1"s in your string, just use a for loop to check. It will be fastest (compared to String functions & Regular Expressions etc).

example:

String binary = "";
binary = "01000010 01000001 01000010 01000101 01000110 01000001 01000011 01000101";

int counted_Ones = 0;

//# check "ones" in string
for( int i=0; i<binary.length(); i++ ) 
{ if(binary.charAt(i) == '1') { counted_Ones++; } }

System.out.println("binary: " + binary);
System.out.println("Number of bit 1 in string: " +  counted_Ones);

Results (from System.out.println ) :

binary: 01000010 01000001 01000010 01000101 01000110 01000001 01000011 01000101
Number of bit 1 in string: 20

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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