พิมพ์จำนวนเต็มในรูปแบบไบนารีใน Java


277

ฉันมีตัวเลขและฉันต้องการพิมพ์เป็นเลขฐานสอง ฉันไม่ต้องการที่จะทำมันด้วยการเขียนอัลกอริธึมมีฟังก์ชั่นบิวท์อินในจาวาไหม?

คำตอบ:


434

สมมติว่าคุณหมายถึง "built-in":

int x = 100;
System.out.println(Integer.toBinaryString(x));

โปรดดูเอกสารจำนวนเต็ม

( Longมีวิธีที่คล้ายกันBigIntegerมีวิธีอินสแตนซ์ที่คุณสามารถระบุ radix ได้)


2
สิ่งนี้ทำให้ 0 ของชั้นนำ
Abu Ruqaiyah

1
@AbuRuqaiyah: OP ไม่เคยพูดถึงศูนย์ชั้นนำและเราต้องการที่จะรู้ว่าพวกเขาคาดว่าจะมีหลายสิ่งสำหรับ ...
Jon Skeet

@AbuRuqaiyah หากคุณต้องการเลขศูนย์นำหน้ามี System.out.printf () ซึ่งให้การควบคุมที่ดีแก่คุณ
NomadMaker

246

ที่นี่ไม่จำเป็นต้องขึ้นอยู่กับไบนารีหรือรูปแบบอื่น ๆ ... ฟังก์ชั่นที่ยืดหยุ่นในตัวสามารถใช้งานได้ซึ่งจะพิมพ์รูปแบบใดก็ได้ที่คุณต้องการในโปรแกรมของคุณ .. Integer.toString (int, ตัวแทน);

Integer.toString(100,8) // prints 144 --octal representation

Integer.toString(100,2) // prints 1100100 --binary representation

Integer.toString(100,16) //prints 64 --Hex representation

ทดสอบด้วยตัวเลขต่าง ๆ , ลบ, บวก, ใหญ่, เล็ก
Tertium

8
toBinaryStringใช้เอาต์พุตส่วนเสริมของทั้งสองtoStringปกปิดหมายเลขฐานที่ระบุและวางเครื่องหมายลบไว้ด้านหน้าดังนั้นtoString(-8, 2) == "-1000"
Joe


21

ฉันต้องการบางอย่างเพื่อพิมพ์สิ่งต่าง ๆ ออกมาอย่างดีและแยกบิตทุกบิต กล่าวอีกนัยหนึ่งแสดงศูนย์นำหน้าและแสดงดังนี้:

n = 5463
output = 0000 0000 0000 0000 0001 0101 0101 0111

ดังนั้นนี่คือสิ่งที่ฉันเขียน:

/**
 * Converts an integer to a 32-bit binary string
 * @param number
 *      The number to convert
 * @param groupSize
 *      The number of bits in a group
 * @return
 *      The 32-bit long bit string
 */
public static String intToString(int number, int groupSize) {
    StringBuilder result = new StringBuilder();

    for(int i = 31; i >= 0 ; i--) {
        int mask = 1 << i;
        result.append((number & mask) != 0 ? "1" : "0");

        if (i % groupSize == 0)
            result.append(" ");
    }
    result.replace(result.length() - 1, result.length(), "");

    return result.toString();
}

เรียกใช้แบบนี้:

public static void main(String[] args) {
    System.out.println(intToString(5463, 4));
}

ทำไมresult.replace(result.length() - 1, result.length(), "");ต้องมี? ขณะที่เราผ่านintซึ่งมีอยู่แล้ว 32 บิต สิ่งที่เรากำลังแทนที่ในบรรทัดสุดท้ายที่สอง?
Parth

1
@Parth ในแต่ละขั้นตอนเราจะต่อท้ายอักขระเว้นวรรค ("") ที่ส่วนท้ายของสตริง บรรทัดที่คุณกล่าวถึงจะกำจัดอักขระช่องว่างที่ต่อท้าย เป็นหลักคุณสามารถเรียกฟังก์ชั่นStringของชั้นเรียนtrimเพื่อให้ได้ผลเช่นเดียวกัน
Maghoumi

คุณสามารถทำสิ่งนี้ได้ง่ายขึ้นและมีประสิทธิภาพมากขึ้นโดยการเพิ่ม 0x100000000 ให้เป็นจำนวนแล้วแปลงมันให้ยาวแล้วละทิ้งผู้นำอันดับที่ 1
Marquis of Lorne

7

โรงเรียนเก่า:

    int value = 28;
    for(int i = 1, j = 0; i < 256; i = i << 1, j++)
        System.out.println(j + " " + ((value & i) > 0 ? 1 : 0));

ฉันคิดSystem.out.printlnและ&สร้างไว้ภายใน)
David Williams

1
เพิ่งรู้ว่าฉันแสดงความคิดเห็นหลังจาก 3 ปีของคำตอบ ... ฮ่า ๆ
rajugaadu

7
public static void main(String[] args) 
{
    int i = 13;
    short s = 13;
    byte b = 13;

    System.out.println("i: " + String.format("%32s", 
            Integer.toBinaryString(i)).replaceAll(" ", "0"));

    System.out.println("s: " + String.format("%16s", 
            Integer.toBinaryString(0xFFFF & s)).replaceAll(" ", "0"));

    System.out.println("b: " + String.format("%8s", 
            Integer.toBinaryString(0xFF & b)).replaceAll(" ", "0"));

}

เอาท์พุท:

i: 00000000000000000000000000001101
s: 0000000000001101
b: 00001101

6

ตรวจสอบตรรกะนี้สามารถแปลงตัวเลขเป็นฐานใด ๆ

public static void toBase(int number, int base) {
    String binary = "";
    int temp = number/2+1;
    for (int j = 0; j < temp ; j++) {
        try {
            binary += "" + number % base;

            number /= base;
        } catch (Exception e) {
        }
    }
    for (int j = binary.length() - 1; j >= 0; j--) {
        System.out.print(binary.charAt(j));
    }
}

หรือ

StringBuilder binary = new StringBuilder();
int n=15;
while (n>0) {
    if((n&1)==1){
        binary.append(1);
    }else
        binary.append(0);
    n>>=1;
}
System.out.println(binary.reverse());

1
สำหรับอินพุตเป็น 0, `if (a == 0) {binary.append (0); System.out.println (binary.toString ()); กลับ; } `เราจำเป็นต้องเพิ่มบรรทัดนี้ในโซลูชันที่สองด้านบนขณะที่วนซ้ำ
Imran

4

นี่เป็นวิธีที่ง่ายที่สุดในการพิมพ์การแทนค่าเลขฐานสองภายในของจำนวนเต็ม ตัวอย่างเช่น : ถ้าเรารับ n เป็น 17 ผลลัพธ์จะเป็น: 0000 0000 0000 0000 0000 0000 0001 0001

void bitPattern(int n) {

        int mask = 1 << 31;
        int count = 0;
        while(mask != 0) {
            if(count%4 == 0)
                System.out.print(" ");

            if((mask&n) == 0) 

                System.out.print("0");



            else 
                System.out.print("1");


            count++;
            mask = mask >>> 1;


    }
    System.out.println();
}

4

ลองดูสิ หากขอบเขตนั้นจะพิมพ์เฉพาะค่าไบนารีของค่าจำนวนเต็มที่กำหนด มันอาจเป็นบวกหรือลบ

      public static void printBinaryNumbers(int n) {
        char[] arr = Integer.toBinaryString(n).toCharArray();
        StringBuilder sb = new StringBuilder();
        for (Character c : arr) {
          sb.append(c);
        }
        System.out.println(sb);
      }

อินพุต

5

เอาท์พุต

101


2

โซลูชันที่ใช้มาสก์การแสดงผล 32 บิต

public static String toBinaryString(int n){

    StringBuilder res=new StringBuilder();
    //res= Integer.toBinaryString(n); or
    int displayMask=1<<31;
    for (int i=1;i<=32;i++){
        res.append((n & displayMask)==0?'0':'1');
        n=n<<1;
        if (i%8==0) res.append(' ');
    }

    return res.toString();
}


 System.out.println(BitUtil.toBinaryString(30));


O/P:
00000000 00000000 00000000 00011110 

2

ทางออกที่ง่ายและสวยที่สุด

public static String intToBinaryString(int integer, int numberOfBits) {

    if (numberOfBits > 0) {     // To prevent FormatFlagsConversionMismatchException.

        String nBits = String.format("%" + numberOfBits + "s",      // Int to bits conversion
                Integer.toBinaryString(integer))
                .replaceAll(" ","0"); 

        return nBits;   // returning the Bits for the given int.
    }

    return null;        // if the numberOfBits is not greater than 0, returning null.
}

1

มีคำตอบที่ดีที่โพสต์ไว้ที่นี่สำหรับคำถามนี้ แต่นี่เป็นวิธีที่ฉันลองด้วยตัวเอง (และอาจเป็นตรรกะที่ง่ายที่สุดตาม→ โมดูโล / หาร / เพิ่ม ):

        int decimalOrBinary = 345;
        StringBuilder builder = new StringBuilder();

        do {
            builder.append(decimalOrBinary % 2);
            decimalOrBinary = decimalOrBinary / 2;
        } while (decimalOrBinary > 0);

        System.out.println(builder.reverse().toString()); //prints 101011001

0

คำถามนั้นยุ่งยากในภาษาจาวา (และอาจเป็นภาษาอื่นด้วย)

Integer เป็นชนิดข้อมูลที่เซ็นชื่อแบบ 32 บิตแต่ Integer.toBinaryString () ส่งคืนการแทนค่าสตริงของอาร์กิวเมนต์จำนวนเต็มเป็นจำนวนเต็มที่ไม่ได้ลงนามในฐาน 2

ดังนั้น Integer.parseInt (Integer.toBinaryString (X), 2) สามารถสร้างข้อยกเว้น (ลงชื่อเมื่อเทียบกับไม่ได้ลงนาม)

วิธีที่ปลอดภัยคือใช้ Integer.toString (X, 2) สิ่งนี้จะสร้างสิ่งที่สง่างามน้อยลง:

-11110100110

แต่มันใช้งานได้ !!!


เขาต้องการพิมพ์ไม่ใช่แยกวิเคราะห์
มาร์ควิสแห่ง Lorne

System.out.println (Integer.toString (X 2));
นินจา

0

ฉันคิดว่ามันเป็นอัลกอริทึมที่ง่ายที่สุดจนถึงตอนนี้ (สำหรับผู้ที่ไม่ต้องการใช้ฟังก์ชันในตัว):

public static String convertNumber(int a)  { 
              StringBuilder sb=new StringBuilder();
              sb.append(a & 1);
              while ((a>>=1) != 0)  { 
                  sb.append(a & 1);
               }
              sb.append("b0");
              return sb.reverse().toString();
  }

ตัวอย่าง:

convertNumber (1) -> "0b1"

convertNumber (5) -> "0b101"

convertNumber (117) -> "0b1110101"

วิธีการทำงาน:ในขณะที่ลูปย้าย a-number ไปทางขวา (แทนที่บิตสุดท้ายด้วย second-to-last, etc) รับค่าบิตสุดท้ายและวางใน StringBuilder ซ้ำจนกว่าจะไม่มีบิตเหลืออยู่ (นั่นคือเมื่อ A = 0)


0
    for(int i = 1; i <= 256; i++)
    {
        System.out.print(i + " "); //show integer
        System.out.println(Integer.toBinaryString(i) + " "); //show binary
        System.out.print(Integer.toOctalString(i) + " "); //show octal
        System.out.print(Integer.toHexString(i) + " "); //show hex

    }

3
ขอบคุณมากสำหรับคำตอบ แต่โปรดเพิ่มรายละเอียดเพิ่มเติมและ / หรือข้อมูลและวิธีการที่จะแก้ปัญหาถามเพื่อให้ผู้อื่นสามารถเข้าใจได้โดยไม่ต้องขอชี้แจง :)
koceeng

0

ลองด้วยวิธีนี้:

public class Bin {
  public static void main(String[] args) {
    System.out.println(toBinary(0x94, 8));
  }

  public static String toBinary(int a, int bits) {
    if (--bits > 0)
        return toBinary(a>>1, bits)+((a&0x1)==0?"0":"1");
    else 
        return (a&0x1)==0?"0":"1";
  }

}

10010100


0

การแทนค่าไบนารีของ int x ที่ได้รับพร้อมเลขศูนย์ด้านซ้าย

org.apache.commons.lang3.StringUtils.leftPad(Integer.toBinaryString(x), 32, '0')

0

ป้อนตัวเลขทศนิยมใด ๆ เป็นอินพุต หลังจากนั้นเราดำเนินการเช่นโมดูโลและการหารเพื่อแปลงอินพุตที่กำหนดเป็นเลขฐานสอง นี่คือซอร์สโค้ดของโปรแกรม Java เพื่อแปลงค่าจำนวนเต็มเป็นไบนารีและจำนวนบิตของไบนารีนี้สำหรับเลขฐานสิบของเขา โปรแกรม Java ได้รับการคอมไพล์และรันบนระบบ Windows ได้สำเร็จ เอาท์พุทของโปรแกรมจะแสดงด้านล่าง

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int integer ;
        String binary = "";    //   here we count "" or null 
                               //   just String binary = null;
        System.out.print("Enter the binary Number: ");
        integer = sc.nextInt();

        while(integer>0)
        {
            int x = integer % 2;
            binary = x + binary;
            integer = integer / 2;  
        }
        System.out.println("Your binary number is : "+binary);
        System.out.println("your binary length : " + binary.length());
    }
}

0

เนื่องจากไม่ยอมรับคำตอบคำถามของคุณอาจเกี่ยวกับวิธีการเก็บจำนวนเต็มในไฟล์ไบนารี java.io.DataOutputStream อาจเป็นสิ่งที่คุณกำลังมองหา: https://docs.oracle.com/javase/8/docs/api/java/io/DataOutputStream.html

DataOutputStream os = new DataOutputStream(outputStream);
os.writeInt(42);
os.flush();
os.close();

2
การพิมพ์ครั้งส่วนใหญ่หมายถึงการเขียนสิ่งที่คอนโซลไม่เก็บไว้ในไฟล์ คำตอบของคุณอาจมีประโยชน์หากถูกขอให้จัดลำดับข้อมูลเป็นไฟล์
Alain-Michel Chomnoue N

แน่นอน แต่เนื่องจากผู้ถามไม่ยอมรับคำตอบใด ๆ ฉันจึงเดาว่าคำถามของเขาไม่ถูกต้อง
Christian Charbula

0

คุณสามารถใช้บิตมาสก์ (1 << k) และทำและดำเนินการด้วยหมายเลข! << << k มีตำแหน่ง k ที่หนึ่งบิต!

private void printBits(int x) {
    for(int i = 31; i >= 0; i--) {
        if((x & (1 << i)) != 0){
            System.out.print(1);
        }else {
            System.out.print(0);
        }
    }
    System.out.println();
}

-2

ทำงานกับค่าที่ลงชื่อและไม่ได้ลงชื่อใช้การจัดการบิตที่มีประสิทธิภาพและสร้างศูนย์แรกทางด้านซ้าย

public static String representDigits(int num) {

        int checkBit = 1 << (Integer.SIZE * 8 - 2 );    // avoid the first digit        
        StringBuffer sb = new StringBuffer();

        if (num < 0 ) {     // checking the first digit
            sb.append("1");
        } else {
            sb.append("0");
        }

        while(checkBit != 0) {          
            if ((num & checkBit) == checkBit){
                sb.append("1");
            } else {
                sb.append("0");
            }           
            checkBit >>= 1;     
        }       

        return sb.toString();
    }
โดยการใช้ไซต์ของเรา หมายความว่าคุณได้อ่านและทำความเข้าใจนโยบายคุกกี้และนโยบายความเป็นส่วนตัวของเราแล้ว
Licensed under cc by-sa 3.0 with attribution required.