Programing

JavaScript에서 정수를 이진수로 변환하는 방법은 무엇입니까?

lottogame 2020. 4. 2. 08:10
반응형

JavaScript에서 정수를 이진수로 변환하는 방법은 무엇입니까?


이진수로 양수 또는 음수의 정수를보고 싶습니다.

이 질문 보다는 JavaScript에 대한 것입니다.


이 답변은 Number.MAX_SAFE_INTEGER(또는 2**53-1)와 (과 ) 사이의 절대 값으로 정수를 처리하려고합니다 2**31. 현재 솔루션은 32 비트 내의 부호있는 정수만 처리하지만이 솔루션은 float64ToInt64Binary()다음을 사용하여 64 비트 2의 보수 형식으로 출력됩니다 .

// IIFE to scope internal variables
var float64ToInt64Binary = (function () {
  // create union
  var flt64 = new Float64Array(1)
  var uint16 = new Uint16Array(flt64.buffer)
  // 2**53-1
  var MAX_SAFE = 9007199254740991
  // 2**31
  var MAX_INT32 = 2147483648

  function uint16ToBinary() {
    var bin64 = ''

    // generate padded binary string a word at a time
    for (var word = 0; word < 4; word++) {
      bin64 = uint16[word].toString(2).padStart(16, 0) + bin64
    }

    return bin64
  }

  return function float64ToInt64Binary(number) {
    // NaN would pass through Math.abs(number) > MAX_SAFE
    if (!(Math.abs(number) <= MAX_SAFE)) {
      throw new RangeError('Absolute value must be less than 2**53')
    }

    var sign = number < 0 ? 1 : 0

    // shortcut using other answer for sufficiently small range
    if (Math.abs(number) <= MAX_INT32) {
      return (number >>> 0).toString(2).padStart(64, sign)
    }

    // little endian byte ordering
    flt64[0] = number

    // subtract bias from exponent bits
    var exponent = ((uint16[3] & 0x7FF0) >> 4) - 1022

    // encode implicit leading bit of mantissa
    uint16[3] |= 0x10
    // clear exponent and sign bit
    uint16[3] &= 0x1F

    // check sign bit
    if (sign === 1) {
      // apply two's complement
      uint16[0] ^= 0xFFFF
      uint16[1] ^= 0xFFFF
      uint16[2] ^= 0xFFFF
      uint16[3] ^= 0xFFFF
      // propagate carry bit
      for (var word = 0; word < 3 && uint16[word] === 0xFFFF; word++) {
        // apply integer overflow
        uint16[word] = 0
      }

      // complete increment
      uint16[word]++
    }

    // only keep integer part of mantissa
    var bin64 = uint16ToBinary().substr(11, Math.max(exponent, 0))
    // sign-extend binary string
    return bin64.padStart(64, sign)
  }
})()

console.log('8')
console.log(float64ToInt64Binary(8))
console.log('-8')
console.log(float64ToInt64Binary(-8))
console.log('2**33-1')
console.log(float64ToInt64Binary(2**33-1))
console.log('-(2**33-1)')
console.log(float64ToInt64Binary(-(2**33-1)))
console.log('2**53-1')
console.log(float64ToInt64Binary(2**53-1))
console.log('-(2**53-1)')
console.log(float64ToInt64Binary(-(2**53-1)))
console.log('2**52')
console.log(float64ToInt64Binary(2**52))
console.log('-(2**52)')
console.log(float64ToInt64Binary(-(2**52)))
console.log('2**52+1')
console.log(float64ToInt64Binary(2**52+1))
console.log('-(2**52+1)')
console.log(float64ToInt64Binary(-(2**52+1)))
.as-console-wrapper {
  max-height: 100% !important;
}

이 답변은 다음과 같이 IEEE-754 배정 밀도 부동 소수점 형식을 많이 처리 합니다.

IEEE-754 배정 밀도 부동 소수점 형식

   seee eeee eeee ffff ffff ffff ffff ffff ffff ffff ffff ffff ffff ffff ffff ffff
   ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
   [    uint16[3]    ] [    uint16[2]    ] [    uint16[1]    ] [    uint16[0]    ]
   [                                   flt64[0]                                  ]

   little endian byte ordering

   s = sign = uint16[3] >> 15
   e = exponent = (uint16[3] & 0x7FF) >> 4
   f = fraction

솔루션이 작동하는 방식은 리틀 엔디안 바이트 순서로 64 비트 부동 소수점 숫자와 부호없는 16 비트 정수 배열 사이에 통합을 만드는 것입니다. 정수 입력 범위의 유효성을 검사 한 후 입력을 버퍼의 배정 밀도 부동 소수점 숫자로 캐스트 한 다음 유니온을 사용하여 값에 대한 비트 액세스 권한을 얻고 바이어스되지 않은 이진 지수 및 분수 비트를 기반으로 이진 문자열을 계산합니다.

이 솔루션은 사용 가능한 폴리 필String#padStart()있는을 사용 하는 것을 제외하고는 순수한 ECMAScript 5로 구현 됩니다 .


function dec2bin(dec){
    return (dec >>> 0).toString(2);
}

dec2bin(1);    // 1
dec2bin(-1);   // 11111111111111111111111111111111
dec2bin(256);  // 100000000
dec2bin(-256); // 11111111111111111111111100000000

Number.toString(2)함수 를 사용할 수 있지만 음수를 나타낼 때 문제가 있습니다. 예를 들어, (-1).toString(2)출력은 "-1"입니다.

이 문제를 해결하려면 부호없는 오른쪽 시프트 비트 연산자 ( >>>)를 사용하여 숫자를 부호없는 정수로 강제 변환 할 수 있습니다.

실행 (-1 >>> 0).toString(2)하면 숫자 0 비트가 오른쪽으로 이동하고 숫자 자체는 변경되지 않지만 부호없는 정수로 표시됩니다. 위의 코드는 "11111111111111111111111111111111"올바르게 출력 됩니다.

이 질문 에는 추가 설명이 있습니다.

-3 >>> 0 (올바른 논리 이동)은 인수를 부호없는 정수로 강제 변환하므로 32 비트 2의 보수 -3을 얻습니다.


시험

num.toString(2);

2는 기수이며 2와 36 사이의 모든 기저가 될 수 있습니다

여기에 소스

최신 정보:

이것은 양수에만 적용되며 Javascript는 2의 보수 표기법으로 음의 이진 정수를 나타냅니다. 트릭을 수행 해야하는이 작은 기능을 만들었으므로 제대로 테스트하지 않았습니다.

function dec2Bin(dec)
{
    if(dec >= 0) {
        return dec.toString(2);
    }
    else {
        /* Here you could represent the number in 2s compliment but this is not what 
           JS uses as its not sure how many bits are in your number range. There are 
           some suggestions https://stackoverflow.com/questions/10936600/javascript-decimal-to-binary-64-bit 
        */
        return (~dec).toString(2);
    }
}

나는 여기 에서 도움을 받았다


'바이너리로 변환'의 바이너리는 세 가지 주요 사항을 나타낼 수 있습니다. 위치 숫자 시스템, 메모리의 이진 표현 또는 32 비트 비트 열 (64 비트 비트 스트링의 경우 Patrick Roberts의 답변 참조 )

1. 번호 시스템

(123456).toString(2)숫자를 밑이 2 인 숫자 시스템으로 변환합니다 . 이 시스템에서 음수는 10 진수처럼 마이너스 부호로 기록됩니다.

2. 내부 대표

숫자의 내부 표현은 64 비트 부동 소수점 이며이 답변 에서는 몇 가지 제한 사항에 대해 설명 합니다. 자바 스크립트에서 비트 문자열 표현을 만들거나 특정 비트에 액세스하는 쉬운 방법없습니다 .

3. 마스크 및 비트 연산자

MDN에는 비트 연산자의 작동 방식에 대한 개요 가 있습니다. 중요하게 :

비트 연산자는 피연산자를 32 비트 시퀀스 (0과 1)로 취급합니다.

연산이 적용되기 전에 64 비트 부동 소수점 숫자는 32 비트 부호있는 정수로 캐스트됩니다. 그들이 다시 회심 한 후.

다음은 숫자를 32 비트 문자열로 변환하기위한 MDN 예제 코드입니다.

function createBinaryString (nMask) {
  // nMask must be between -2147483648 and 2147483647
  for (var nFlag = 0, nShifted = nMask, sMask = ""; nFlag < 32;
       nFlag++, sMask += String(nShifted >>> 31), nShifted <<= 1);
  return sMask;
}

createBinaryString(0) //-> "00000000000000000000000000000000"
createBinaryString(123) //-> "00000000000000000000000001111011"
createBinaryString(-1) //-> "11111111111111111111111111111111"
createBinaryString(-1123456) //-> "11111111111011101101101110000000"
createBinaryString(0x7fffffff) //-> "01111111111111111111111111111111"

간단한 방법은 ...

Number(42).toString(2);

// "101010"

참고 (x>>>0).toString(2);-x가 양수 이면 기본 에 약간의 문제가 있습니다. >>>를 사용하면서 >>> 메소드의 문제를 해결하는 예제 코드가 있습니다.

(-3>>>0).toString(2);

prints -3 in 2s complement.

1111111111101

실제 사례

C:\>type n1.js
console.log(   (-3 >>> 0).toString(2)    );
C:\>
C:\>node n1.js
11111111111111111111111111111101

C:\>

URL 표시 줄의 또 다른 빠른 증거입니다.

javascript:alert((-3>>>0).toString(2))

참고-결과는 항상 1로 시작하기 때문에 약간의 결함이 있습니다. 음수의 경우 좋습니다. 양수의 경우 시작 부분에 0을 붙여 결과가 실제로 2의 보수가되도록해야합니다. 따라서 (8>>>0).toString(2)1000에서 2를 보완하는 8이 아니라 1000을 생성하지만 0 앞에 두어 0을 곱하면 2에서 2를 보완하는 올바른 8입니다. 적절한 2s 보수에서 0으로 시작하는 모든 비트 문자열은> = 0이고 1로 시작하는 모든 비트 문자열은 음수입니다.

예를 들어 문제가 해결됩니다

// or x=-5  whatever number you want to view in binary  
x=5;   
if(x>0) prepend="0"; else prepend=""; 
alert(prepend+((x>>>0)).toString(2));

다른 솔루션은 Annan의 솔루션입니다 (Annan의 설명과 정의에는 오류가 많지만 올바른 출력을 생성하는 코드가 있습니다) 및 Patrick의 솔루션입니다.

0으로 시작하는 양수와 2의 보수에서 1을 갖는 음수의 사실을 이해하지 못하는 사람은 2s 보수의 SO QnA를 확인할 수 있습니다. “2의 보완”이란 무엇입니까?


비트 배열을 반환하는 고유 한 함수를 작성할 수 있습니다. 숫자를 비트로 변환하는 방법의 예

제수 | 배당 | 비트 / 나머지

2 | 9 | 1

2 | 4 | 0

2 | 2 | 0

~ | 1 | ~

위 행의 예 : 2 * 4 = 8이고 나머지는 1이므로 9 = 1 0 1

function numToBit(num){
    var number = num
    var result = []
    while(number >= 1 ){
        result.unshift(Math.floor(number%2))
        number = number/2
    }
    return result
}

나머지를 아래에서 위로 읽으십시오. 가운데 1에서 숫자 1까지.


나는 다른 접근법을 사용하여 이것을하는 것을 생각해 냈습니다. 내 프로젝트에서이 코드를 사용하지 않기로 결정했지만 누군가에게 유용 할 수 있도록 관련 어딘가에 남겨 두겠다고 생각했습니다.

  • 비트 시프 팅 또는 2의 보수 강제를 사용하지 않습니다.
  • 나오는 비트 수를 선택합니다 ( '8', '16', '32'의 유효한 값을 확인하지만 변경할 수 있다고 생각합니다)
  • 부호있는 정수 또는 부호없는 정수로 처리할지 여부를 선택합니다.
  • 부호 처리 / 부호없는 비트 수와 비트 수의 조합으로 범위 문제를 확인하지만 오류 처리를 향상 시키려고합니다.
  • 또한 비트를 int로 다시 변환하는 함수의 "역"버전이 있습니다. 이 출력을 해석 할 다른 것이 없기 때문에 필요합니다. : D

function intToBitString(input, size, unsigned) {
	if ([8, 16, 32].indexOf(size) == -1) {
		throw "invalid params";
	}
	var min = unsigned ? 0 : - (2 ** size / 2);
        var limit = unsigned ? 2 ** size : 2 ** size / 2;
	if (!Number.isInteger(input) || input < min || input >= limit) {
		throw "out of range or not an int";
	}
	if (!unsigned) {
		input += limit;
	}
	var binary = input.toString(2).replace(/^-/, '');
	return binary.padStart(size, '0');
}

function bitStringToInt(input, size, unsigned) {
	if ([8, 16, 32].indexOf(size) == -1) {
		throw "invalid params";
	}
	input = parseInt(input, 2);
	if (!unsigned) {
		input -= 2 ** size / 2;
	}
	return input;
}


// EXAMPLES

var res;
console.log("(uint8)10");
res = intToBitString(10, 8, true);
console.log("intToBitString(res, 8, true)");
console.log(res);
console.log("reverse:", bitStringToInt(res, 8, true));
console.log("---");

console.log("(uint8)127");
res = intToBitString(127, 8, true);
console.log("intToBitString(res, 8, true)");
console.log(res);
console.log("reverse:", bitStringToInt(res, 8, true));
console.log("---");

console.log("(int8)127");
res = intToBitString(127, 8, false);
console.log("intToBitString(res, 8, false)");
console.log(res);
console.log("reverse:", bitStringToInt(res, 8, false));
console.log("---");

console.log("(int8)-128");
res = intToBitString(-128, 8, false);
console.log("intToBitString(res, 8, true)");
console.log(res);
console.log("reverse:", bitStringToInt(res, 8, true));
console.log("---");

console.log("(uint16)5000");
res = intToBitString(5000, 16, true);
console.log("intToBitString(res, 16, true)");
console.log(res);
console.log("reverse:", bitStringToInt(res, 16, true));
console.log("---");

console.log("(uint32)5000");
res = intToBitString(5000, 32, true);
console.log("intToBitString(res, 32, true)");
console.log(res);
console.log("reverse:", bitStringToInt(res, 32, true));
console.log("---");


이것은 내 코드입니다.

var x = prompt("enter number", "7");
var i = 0;
var binaryvar = " ";

function add(n) {
    if (n == 0) {
        binaryvar = "0" + binaryvar; 
    }
    else {
        binaryvar = "1" + binaryvar;
    }
}

function binary() {
    while (i < 1) {
        if (x == 1) {
            add(1);
            document.write(binaryvar);
            break;
        }
        else {
            if (x % 2 == 0) {
                x = x / 2;
                add(0);
            }
            else {
                x = (x - 1) / 2;
                add(1);
            }
        }
    }
}

binary();

이것이 해결책입니다. 사실은 아주 간단합니다

function binaries(num1){ 
        var str = num1.toString(2)
        return(console.log('The binary form of ' + num1 + ' is: ' + str))
     }
     binaries(3

)

        /*
         According to MDN, Number.prototype.toString() overrides 
         Object.prototype.toString() with the useful distinction that you can 
         pass in a single integer argument. This argument is an optional radix, 
         numbers 2 to 36 allowed.So in the example above, we’re passing in 2 to 
         get a string representation of the binary for the base 10 number 100, 
         i.e. 1100100.
        */

참고 URL : https://stackoverflow.com/questions/9939760/how-do-i-convert-an-integer-to-binary-in-javascript

반응형