Java에서 이진 형식으로 정수 인쇄
숫자가 있는데 이진수로 인쇄하고 싶습니다. 알고리즘을 작성하여하고 싶지 않습니다 .Java에 내장 기능이 있습니까?
"내장"을 의미한다고 가정합니다.
int x = 100;
System.out.println(Integer.toBinaryString(x));
정수 설명서를 참조하십시오 .
( Long
유사한 방법 BigInteger
이 있고 기수를 지정할 수있는 인스턴스 방법이 있습니다.)
여기서는 바이너리 나 다른 형식에만 의존 할 필요가 없습니다. 하나의 유연한 내장 함수를 사용할 수 있습니다. 프로그램에서 원하는 형식을 인쇄합니다. Integer.toString (int, representation);
Integer.toString(100,8) // prints 144 --octal representation
Integer.toString(100,2) // prints 1100100 --binary representation
Integer.toString(100,16) //prints 64 --Hex representation
System.out.println(Integer.toBinaryString(343));
물건을 멋지게 인쇄하고 n 비트마다 비트를 분리하는 것이 필요했습니다. 즉, 앞에 0을 표시하고 다음과 같이 표시하십시오.
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));
}
오래된 학교:
int value = 28;
for(int i = 1, j = 0; i < 256; i = i << 1, j++)
System.out.println(j + " " + ((value & i) > 0 ? 1 : 0));
이 논리가 숫자를 어떤 기본으로 변환 할 수 있는지 확인하십시오.
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());
이것은 정수 의 내부 이진 표현 을 인쇄 하는 가장 간단한 방법 입니다 . 예를 들어, 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();
}
간단히 해보십시오. 범위가 주어진 정수 값의 이진 값만 인쇄하는 경우. 긍정적이거나 부정적 일 수 있습니다.
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
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(0xFFFFFF & b)).replaceAll(" ", "0"));
}
산출:
i: 00000000000000000000000000001101
s: 0000000000001101
b: 00001101
이 질문에 대한 좋은 답변이 여기에 게시되어 있습니다. 그러나 이것이 내가 시도한 방법입니다 (그리고 가장 쉬운 논리 기반 → modulo / divide / add ).
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
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
간단하고 매우 쉬운 솔루션.
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.
}
이 질문은 자바에서 까다 롭습니다 (아마도 다른 언어로).
Integer는 32 비트 부호있는 데이터 형식이지만 Integer.toBinaryString ()은 정수 인수의 문자열 표현을 기수 2 의 부호없는 정수 로 반환합니다 .
따라서 Integer.parseInt (Integer.toBinaryString (X), 2)는 예외 (서명 된 대 서명되지 않은)를 생성 할 수 있습니다.
안전한 방법은 Integer.toString (X, 2); 이것은 덜 우아한 것을 생성합니다 :
-11110100110
그러나 작동합니다 !!!
내장 알고리즘을 사용하지 않으려는 사람들에게는 지금까지 가장 간단한 알고리즘이라고 생각합니다.
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"
작동 방식 : while-loop는 a- 숫자를 오른쪽으로 이동하고 (마지막 비트를 초에서 마지막으로 교체하는 등), 마지막 비트 값을 가져 와서이를 StringBuilder에 넣고, 비트가 없을 때까지 반복합니다. a = 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
}
이 방법으로 시도하십시오 :
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')
입력으로 10 진수를 입력하십시오. 그런 다음 주어진 입력을 이진수로 변환하기 위해 모듈로 및 나누기와 같은 연산을 수행합니다. 다음은 정수 값을 이진으로 변환하기위한 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을 생성합니다.
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();
}
참고 URL : https://stackoverflow.com/questions/5263187/print-an-integer-in-binary-format-in-java
'Programing' 카테고리의 다른 글
OS 독립 경로 'META-INF / LICENSE'와 함께 둘 이상의 파일이 발견되었습니다. (0) | 2020.04.06 |
---|---|
Java로 "unixtime"얻기 (0) | 2020.04.06 |
python matplotlib에서 축 텍스트 회전 (0) | 2020.04.06 |
pg_dump에 비밀번호를 전달하는 방법은 무엇입니까? (0) | 2020.04.06 |
web.config에서 연결 문자열 읽기 (0) | 2020.04.06 |