Преобразование числа в двоичный формат в JavaScript
Преобразование числа в двоичное — довольно сложный процесс. Если мы будем сидеть и преобразовывать числа вручную, результат будет подвержен ошибкам. Как преобразовать число в двоичный формат? В JavaScript для этого не так много встроенных функций. Мы расскажем, как преобразовать число в двоичное в JavaScript.
Создайте функцию для преобразования числа в двоичное в JavaScript
Прежде чем перейти к коду, нам нужно знать процесс преобразования десятичного числа (основание 10) в двоичное число (основание 2). Для простоты в этой статье мы рассмотрим преобразование положительных целых чисел. Следовательно, изменение отрицательных целых чисел и чисел с плавающей запятой выходит за рамки этой статьи.
Понять процесс преобразования
Читаем цифры от старшего к младшему. Следовательно, двоичное значение числа 25 — 1101.
Мы используем следующий набор вычислений, чтобы убедиться, что двоичное значение представляет правильное десятичное число. Каждый бит, представленный в двоичном числе, умножается на 2 , чтобы получить значение позиции бита (начиная с 0).
Код JavaScript для преобразования числа в двоичный формат
Мы создаем следующий код на основе описанного выше метода. Функция convertToBinary1 консоляет двоичный эквивалент десятичного числа, переданного в качестве параметра. Обратите внимание, что мы читаем результат задом наперед. Следовательно, код был создан с учетом всех вышеупомянутых факторов.
Использование итерации
Сделайте копию параметра, переданного функции, и сохраните его во временной переменной num .
Создайте переменную для хранения двоичных битов. По сути, это строка типа, чтобы упростить обработку.
Начните итерацию для генерации двоичных битов и дайте ей продолжаться до тех пор, пока число не перестанет делиться на 2.
На каждой итерации мы делим число на 2 , чтобы получить частное. Мы вычисляем модульность частного. Этот шаг генерирует двоичные биты, поскольку модульность числа с 2 генерирует двоичные биты 0 или 1 .
Добавить двоичный бит, сгенерированный модульным значением, к двоичной переменной, которая содержит двоичные биты, сгенерированные в каждой итерации.
Как только число больше не делится на 2 (проверено с условием (num / 2)> 1), итерация останавливается.
На последнем этапе мы записываем результат в консоль. Таким образом, мы получаем двоичный эквивалент десятичного числа, переданного в качестве параметра этой функции.
Использование рекурсии
Мы можем использовать метод рекурсии для преобразования десятичного бита в двоичный. Этот подход требует меньше строк кода, но требует больше размышлений. Рекурсия останавливается, когда число больше не делится на 2, и продолжает вызывать себя до тех пор, пока не достигнет условия прорыва. Рекурсии элегантны, но потребляют больше памяти для стека вызовов функций, чем для простого итерационного подхода.
Преобразование числа в двоичное с помощью функции toString(2)
Функция toString() хорошо знакома для преобразования числа в строку. Но мы также можем использовать его для преобразования числа в его двоичный формат. Обычно он используется с объектом Number для преобразования числа в двоичный формат. Функция javascript toString(2) при использовании с числовым объектом возвращает двоичный эквивалент числового значения, как показано в примерах ниже. В качестве входных данных метод принимает значение системы счисления. Следовательно, мы можем использовать его для преобразования данного числа в другие базовые системы (например, основание 16 (шестнадцатеричное) и основание восьми (восьмеричное)).
Обратите внимание, что тип возврата метода toString(2) остается строкой. Следовательно, он преобразует число в двоичный бит в строковом формате.
Binary Conversion in JavaScript
This week I had an interview where I was asked to perform an operation using a binary number. It intrigued me to dig into binary numbers a bit more and try to get a bit more comfortable with them.
What is a Binary Number?
To get an idea of what exactly you need to do to convert a number into binary let’s take a look at what exactly a binary number is. Wikipedia’s is not a particularly complicated definition, In mathematics and digital electronics, a binary number is a number expressed in the base-2 numeral system or binary numeral system, which uses only two symbols: typically «0» (zero) and «1» (one).
Converting an Integer to Binary
Alright, so now that we know a binary number is a number expressed in base-2 we can take a look at converting our numbers. In the case that our input is an integer, we can use JavaScript’s toString method to convert our number.
The toString method accepts an argument of the base used to convert a number into a string.
Exit fullscreen mode
That is very simple. But what if our input is not a number but in fact a string? We cannot just call toString on it since it is already a string. Using the parseInt function, we can convert our string into a number and then convert that number into a base-2 string. Let’s see what that looks like.
Exit fullscreen mode
Well that certainly works. But wait, there is an optional argument for the parseInt function that allows us to specify the base to be used when converting a string to an integer. While this does allow us to specify that we are parsing the string into binary, we do not preserve the entire binary sequence but just the first bit.
Exit fullscreen mode
Another issue with the second argument of our parseInt function is that it returns NaN when presented with the number 2 and the base of 2.
Exit fullscreen mode
This is a bit of an issue since 2 can be converted into a binary number. If we take a look at our solution, we can see that we are able to work with the number 2 and return a binary number.
Exit fullscreen mode
Well I guess we will have to settle for converting a string into a number and back into a string. It might seem like a bit of a long way to go but it does ensure that we have the entire binary number to work with.
That’s it, we have converted our input whether a number or a string into a binary number represented as a string. You can convert it back into an integer if you needed to but if your binary number began with a 0, your integer would not match the binary string since the 0 would just be left off.
Exit fullscreen mode
Nevertheless, we have accomplished our goal, the input number was converted to a binary number. From here we can do whatever it is that we need to do with our binary number. The toString method does most of the heavy lifting here as it is the one that manages the conversion to binary.
parseInt()
Функция parseInt() принимает строку в качестве аргумента и возвращает целое число в соответствии с указанным основанием системы счисления.
Интерактивный пример
Синтаксис
Параметры
Значение, которое необходимо проинтерпретировать. Если значение параметра string не принадлежит строковому типу, оно преобразуется в него (с помощью абстрактной операции ToString ). Пробелы в начале строки не учитываются.
Целое число в диапазоне между 2 и 36, представляющее собой основание системы счисления числовой строки string , описанной выше. В основном пользователи используют десятичную систему счисления и указывают 10. Всегда указывайте этот параметр, чтобы исключить ошибки считывания и гарантировать корректность исполнения и предсказуемость результата. Когда основание системы счисления не указано, разные реализации могут возвращать разные результаты.
Возвращаемое значение
Целое число, полученное парсингом (разбором и интерпретацией) переданной строки. Если первый символ не получилось сконвертировать в число, то возвращается NaN .
Описание
Функция parseInt преобразует первый переданный ей аргумент в строковый тип, интерпретирует его и возвращает целое число или значение NaN . Результат (если не NaN ) является целым числом и представляет собой первый аргумент ( string ), рассматривающийся как число в указанной системе счисления ( radix ). Например, основание 10 указывает на преобразование из десятичного числа, 8 — восьмеричного, 16 — шестнадцатеричного и так далее. Если основание больше 10 , то для обозначения цифр больше 9 используются буквы. Например, для шестнадцатеричных чисел (основание 16) используются буквы от A до F .
Если функция parseInt встречает символ, не являющийся числом в указанной системе счисления, она пропускает этот и все последующие символы (даже, если они подходящие) и возвращает целое число, преобразованное из части строки, предшествовавшей этому символу. parseInt отсекает дробную часть числа. Пробелы в начале и конце строки разрешены.
Так как некоторые числа включают символ e в своём строковом представлении (например, 6.022e23 ), то использование parseInt для усечения числовых значений может дать неожиданные результаты, когда используются очень малые или очень большие величины. parseInt не должна использоваться как замена для Math.floor() .
Если основание системы счисления имеет значение undefined (не определено) или равно 0 (или не указано), то JavaScript по умолчанию предполагает следующее:
- Если значение входного параметра string начинается с » 0x » или » 0X «, за основание системы счисления принимается 16, и интерпретации подвергается оставшаяся часть строки.
- Если значение входного параметра string начинается с «0», за основание системы счисления принимается либо 8, либо 10, в зависимости от конкретной реализации. В спецификации ECMAScript 5 прописано использование 10 (десятичная система), но это поддерживается ещё не всеми браузерами, поэтому необходимо всегда указывать основание системы счисления при использовании функцииparseInt .
- Если значение входного параметра string начинается с любого другого символа, система счисления считается десятичной (основание 10).
Если первый символ строки не может быть преобразован в число, parseInt возвращает значение NaN .
С точки зрения математики, значение NaN не является числом в какой-либо системе счисления. Чтобы определить, вернёт ли parseInt значение NaN в качестве результата, можно вызвать функцию isNaN . Если NaN участвует в арифметических операциях, результатом также будет NaN .
How do I convert an integer to binary in JavaScript?
I’d like to see integers, positive or negative, in binary.
Rather like this question, but for JavaScript.
17 Answers 17
You can use Number.toString(2) function, but it has some problems when representing negative numbers. For example, (-1).toString(2) output is "-1" .
To fix this issue, you can use the unsigned right shift bitwise operator ( >>> ) to coerce your number to an unsigned integer.
If you run (-1 >>> 0).toString(2) you will shift your number 0 bits to the right, which doesn’t change the number itself but it will be represented as an unsigned integer. The code above will output "11111111111111111111111111111111" correctly.
This question has further explanation.
-3 >>> 0 (right logical shift) coerces its arguments to unsigned integers, which is why you get the 32-bit two’s complement representation of -3.
The 2 is the radix and can be any base between 2 and 36
UPDATE:
This will only work for positive numbers, Javascript represents negative binary integers in two’s-complement notation. I made this little function which should do the trick, I haven’t tested it out properly:
I had some help from here
A simple way is just.
The binary in ‘convert to binary’ can refer to three main things. The positional number system, the binary representation in memory or 32bit bitstrings. (for 64bit bitstrings see Patrick Roberts’ answer)
1. Number System
(123456).toString(2) will convert numbers to the base 2 positional numeral system. In this system negative numbers are written with minus signs just like in decimal.
2. Internal Representation
The internal representation of numbers is 64 bit floating point and some limitations are discussed in this answer. There is no easy way to create a bit-string representation of this in javascript nor access specific bits.
3. Masks & Bitwise Operators
MDN has a good overview of how bitwise operators work. Importantly:
Bitwise operators treat their operands as a sequence of 32 bits (zeros and ones)
Before operations are applied the 64 bit floating points numbers are cast to 32 bit signed integers. After they are converted back.
Here is the MDN example code for converting numbers into 32-bit strings.
This answer attempts to address inputs with an absolute value in the range of 214748364810 (2 31 ) – 900719925474099110 (2 53 -1).
In JavaScript, numbers are stored in 64-bit floating point representation, but bitwise operations coerce them to 32-bit integers in two’s complement format, so any approach which uses bitwise operations restricts the range of output to -214748364810 (-2 31 ) – 214748364710 (2 31 -1).
However, if bitwise operations are avoided and the 64-bit floating point representation is preserved by using only mathematical operations, we can reliably convert any safe integer to 64-bit two’s complement binary notation by sign-extending the 53-bit twosComplement :
For older browsers, polyfills exist for the following functions and values:
As an added bonus, you can support any radix (2–36) if you perform the two’s complement conversion for negative numbers in ⌈64 / log2(radix)⌉ digits by using BigInt :
If you are interested in my old answer that used an ArrayBuffer to create a union between a Float64Array and a Uint16Array , please refer to this answer’s revision history.
A solution i’d go with that’s fine for 32-bits, is the code the end of this answer, which is from developer.mozilla.org(MDN), but with some lines added for A)formatting and B)checking that the number is in range.
Some suggested x.toString(2) which doesn’t work for negatives, it just sticks a minus sign in there for them, which is no good.
Fernando mentioned a simple solution of (x>>>0).toString(2); which is fine for negatives, but has a slight issue when x is positive. It has the output starting with 1, which for positive numbers isn’t proper 2s complement.
Anybody that doesn’t understand the fact of positive numbers starting with 0 and negative numbers with 1, in 2s complement, could check this SO QnA on 2s complement. What is “2's Complement”?
A solution could involve prepending a 0 for positive numbers, which I did in an earlier revision of this answer. And one could accept sometimes having a 33bit number, or one could make sure that the number to convert is within range -(2^31)<=x<2^31-1. So the number is always 32bits. But rather than do that, you can go with this solution on mozilla.org
Patrick’s answer and code is long and apparently works for 64-bit, but had a bug that a commenter found, and the commenter fixed patrick’s bug, but patrick has some "magic number" in his code that he didn’t comment about and has forgotten about and patrick no longer fully understands his own code / why it works.
Annan had some incorrect and unclear terminology but mentioned a solution by developer.mozilla.org
The solution there works for 32-bit numbers.
The code is pretty compact, a function of three lines.
But I have added a regex to format the output in groups of 8 bits. Based on How to format a number with commas as thousands separators? (I just amended it from grouping it in 3s right to left and adding commas, to grouping in 8s right to left, and adding spaces)
And, while mozilla made a comment about the size of nMask(the number fed in)..that it has to be in range, they didn’t test for or throw an error when the number is out of range, so i’ve added that.
I’m not sure why they named their parameter ‘nMask’ but i’ll leave that as is.
You can write your own function that returns an array of bits. Example how to convert number to bits
Divisor| Dividend| bits/remainder
2 | 9 | 1
2 | 4 | 0
2 | 2 | 0
example of above line: 2 * 4 = 8 and remainder is 1 so 9 = 1 0 0 1
Read remainders from bottom to top. Digit 1 in the middle to top.
This is how I manage to handle it:
we can also calculate the binary for positive or negative numbers as below:
You could use a recursive solution:
An actual solution that logic can be implemented by any programming language:
If you sure it is positive only:
If can negative or positive —
I’d like to see integers, positive or negative, in binary.
This is an old question and I think there are very nice solutions here but there is no explanation about the use of these clever solutions.
First, we need to understand that a number can be positive or negative. Also, JavaScript provides a MAX_SAFE_INTEGER constant that has a value of 9007199254740991 . The reasoning behind that number is that JavaScript uses double-precision floating-point format numbers as specified in IEEE 754 and can only safely represent integers between -(2^53 — 1) and 2^53 — 1 .
So, now we know the range where numbers are "safe". Also, JavaScript ES6 has the built-in method Number.isSafeInteger() to check if a number is a safe integer.
Logically, if we want to represent a number n as binary, this number needs a length of 53 bits, but for better presentation lets use 7 groups of 8 bits = 56 bits and fill the left side with 0 or 1 based on its sign using the padStart function.
Next, we need to handle positive and negative numbers: positive numbers will add 0 s to the left while negative numbers will add 1 s. Also, negative numbers will need a two’s-complement representation. We can easily fix this by adding Number.MAX_SAFE_INTEGER + 1 to the number.
For example, we want to represent -3 as binary, lets assume that Number.MAX_SAFE_INTEGER is 00000000 11111111 (255) then Number.MAX_SAFE_INTEGER + 1 will be 00000001 00000000 (256) . Now lets add the number Number.MAX_SAFE_INTEGER + 1 — 3 this will be 00000000 11111101 (253) but as we said we will fill with the left side with 1 like this 11111111 11111101 (-3) , this represent -3 in binary.
Another algorithm will be we add 1 to the number and invert the sign like this -(-3 + 1) = 2 this will be 00000000 00000010 (2) . Now we invert every bit like this 11111111 11111101 (-3) again we have a binary representation of -3 .