Modulous for a non-0 based range of numbers - javascript

I'm trying to manipulate the ASCII code for a given string of letters (all caps). In the example below, I increment the ASCII code by one and output it to #newText.
<h2 id="text">ABCXYZ</h2>
<h2 id="newText">placeholder</h2>
var text = document.getElementById("text").firstChild.nodeValue;
var newText = "";
for (i=0; i < text.length; i++){
newText = newText + String.fromCharCode(text.charCodeAt(i)+1);
}
document.getElementById("newText").firstChild.nodeValue = newText;
JSFiddle: http://jsfiddle.net/KatieK/gg9Hx/19/
The problem is that Z is changed into a [. (This makes sense, since the ASCII range for A-Z is 65-90, and [ has an ASCII value of 91.) Instead, I want Z to transform into A.
I've tried modulus to get the ASCII values to wrap around, but I'm having difficulty with the non-0 range of ASCII values.
If x = 91;, then console.log(((x-65)%26)+65); results in 65, which is fine. But if x = 64; then the same formula results in 64, when I want it to to be 90.
How can I account for the non-zero range of the capital letters' ASCII values when incrementing and modulating them? In this example, I'd like to transform 91 into 65, 92 into 66, 93 into 67, 64 into 90, 63 into 89, and 62 into 88 as examples.

You could just pad x with another 26 to handle values within 26 below 65.
console.log(((x+26-65)%26)+65);
If you need more padding, just add some other multiple of 26.

Well, A-Z is 26 characters so do your arithmetic modulo 26. Then encode the result (0...25) as the desired character range, which in this case is as simple as adding 65.
Similarly to decode, first convert from the character range to numbers and then apply arithmetic.

You'll need a condition to see if the number is lower than 65 or higher than 90, then just do the opposite of what you're currently doing for numbers over 90
var x = text.charCodeAt(i)+1;
x = x > 90 ? ((x-65)%26)+65 : x < 65 ? (((x+65)%26)+65) : x;
newText = newText + String.fromCharCode(x);
FIDDLE
To make it work with any number, use
x = x > 90 ? x-(Math.ceil((x-90)/26)*26) : x < 65 ? x+(Math.ceil((65-x)/26)*26) : x;

You have the first part of the solution, console.log(((x-65)%26)+65);. As you noticed, it works in some cases but not others. So use it in the cases where it works and use something else in the other cases. Just write code that does what you want.

Related

how to find lexicographic string based on specified ranking

Consider all the strings of length 6 composed of capital Latin letters (A - Z), sorted in lexicographic order. The string AAAAAA is the first. The string AAAAAZ is the 26th . The 27th is AAAABA. The hint to this problem is the Nth string where N is the number of primes less than 2^ 30 − M . M is a permutation of 123456789, and we won’t tell you which one it is, but we will give you the following constraints to reduce the space of possibilities:
M is divisible by 567.
M starts with 2, ends with 4, and the middle digit is 8.
I managed to find M and the Nth, but I am not able to find a solution on how to find the right string based on the ranking. Please note that I found 9 possibilities on the ranking (Nth) which are:
43973488
43929860
41992802
41914646
41831591
41232030
41066565
40861259
40167328
Thank you for your help.
you need to convert the numbers to base 26 , and match each digit to the related chars
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
function convertToBase26Strings(number) {
number = number - 1 ;
var res = ""
while(number >= chars.length ) {
var i = number % chars.length ;
number = Math.floor(number / chars.length)
res += chars[i];
}
res += chars[number];
return res.split("").reverse().join("").padStart(6 , "A");
}
console.log(convertToBase26Strings(1));
console.log(convertToBase26Strings(26));
console.log(convertToBase26Strings(27));

What's the most efficient way of getting position of least significant bit of a number in javascript?

I got some numbers and I need to get how much they should be shifted for their lower bit to be at position 0.
ex:
0x40000000 => 30 because 0x40000000 >> 30 = 1
768 = 512+256 => 8
This works
if (Math.log2(x) == 31)
return 31;
if (Math.log2(x) > 31)
x = x & 0x7FFFFFFF;
return Math.log2(x & -x)
Is there any more efficient or elegant way (builtin ?) to do this in javascript ?
You cannot get that result immediately with a builtin function, but you can avoid using Math.log2. There is a little known function Math.clz32, which counts the number of leading zeroes of a number in its 32-bit binary representation. Use it like this:
function countTrailingZeroes(n) {
n |= 0; // Turn to 32 bit range
return n ? 31 - Math.clz32(n & -n) : 0;
}
console.log(countTrailingZeroes(0b11100)); // 2
The ternary expression is there to catch the value n=0, which is like a degenerate case: it has no 1-bit.

Algorith problem Decode Hex to set output

I got an algorithm that I need to solve. Unfortunately, I can't even find a clue about a solution. Please help me to understand how to solve this problem.
The problem
An imaginary pen input device sends hex data to the device to display a line with color.
Examples Draw simple Green Line
Set color to green, draw a line from (0,0) to (4000, 4000). Filled circle in this diagram indicates a pen down
position, empty circle indicates pen up position.
Input Data: F0A04000417F4000417FC040004000804001C05F205F20804000
Output: CLR; CO 0 255 0 255; MV (0, 0); PEN DOWN;
MV (4000, 4000); PEN UP;
I got the information about each output.
This code is for encoding hex to binary. I guess that the solution would encode the hex to binary, and manipulate it to set correct output.
function hex2bin(hex){
return (parseInt(hex, 16).toString(2))}
The expected result has the same output as Examaple's with the input data.
First of all, some important information is missing from your question: how the numbers like 4000 (in the result) are encoded in the hex format.
I think I could derive it from the example though
The peculiar numeric encoding
Numbers seem to be encoded with 2 bytes (4 hex characters) each, where the most significant bits of these 2 bytes (bits 7 and 15) do not contribute to the value (they are always zero).
Furthermore, the remaining 14 bits are encoded in offset binary, where the most significant of those 14 bits is the inverted sign bit.
This means that "4000" is zero, "0000" is -8192 (the minimum), and "7F7F" is 8191 (the maximum). Note that the one but last character cannot be more than 7, since that would set a bit that is not used in this (custom) encoding.
This was the hardest part to derive from the little info you provided.
On the Example
The input example you provided can be broken down into pieces like this:
opcode | argument(s)
-------+----------------------------
"F0" |
"A0" | "4000" "417F" "4000" "417F"
"C0" | "4000" "4000"
"80" | "4001"
"C0" | "5F20" "5F20"
"80" | "4000"
Using the numeric conversion discussed above, this would translate to:
opcode | argument(s)
-------+------------
240 |
160 | 0 255 0 255
192 | 0 0
128 | 1
192 | 4000 4000
128 | 0
And then it is a matter of following the instructions to turn that into the required output.
So the algorithm could first decode the input string into commands, where each command consists of an opcode and zero or more numeric arguments.
And then those commands could be turned into the required output by keeping track of whether the pen is down and what the current coordinates are:
function decode(hex) {
let commands = [];
let command;
for (let i = 0, len; i < hex.length; i+=len) {
// Opcodes take 1 byte (i.e. 2 hex characters), and
// numbers take 2 bytes (4 characters)
len = hex[i] >= "8" ? 2 : 4;
let num = parseInt(hex.slice(i, i+len), 16);
if (len === 2) { // opcode
command = []; // start a new command
commands.push(command);
} else { // number
// The encoded format is a custom one. This seems to be it:
num = ((num & 0x7F00) >> 1) + (num & 0x7F) - 0x2000;
}
command.push(num); // push opcode or argument in current command
}
return commands;
}
function disassemble(hex) {
let isPenDown = false;
let x = 0, y = 0;
let output = "";
let commands = decode(hex);
for (let [opcode, ...args] of commands) {
if (opcode === 0xF0) {
x = y = 0;
isPenDown = false;
output += "CLR;\n";
} else if (opcode === 0x80) {
isPenDown = args[0] > 0;
output += "PEN " + (isPenDown ? "DOWN" : "UP") + ";\n";
} else if (opcode === 0xA0) {
output += "CO " + args.join(" ") + ";\n";
} else if (opcode === 0xC0) {
let allPos = "", lastPos;
for (let i = 0; i < args.length; i+=2) {
x += args[i];
y += args[i+1];
lastPos = ` (${x}, ${y})`;
if (isPenDown) allPos += lastPos;
}
output += "MV" + (allPos || lastPos) + ";\n";
} // else: ignore unknown commands
}
return output;
}
// Sample:
console.log(disassemble("F0A04000417F4000417FC040004000804001C05F205F20804000"));
More to do
In the screenshot of the problem, near the end, there is also mention of clipping movements to a bounding box. This goes beyond your question about decoding the hex input, so I will leave it at this. For the interested, you could check out Q&A about calculating line segment intersections, such as this one.

Math behind obtaining a charaters Ascii code

So, basically I am doing some JS exercises and I understand this code, just cant figure out whats the math behind obtaining characters Ascii code in String.fromCharCode function?
why do we decrement by 18?
Have the function LetterChanges(str) take the str parameter being passed and modify it using the following algorithm. Replace every letter in the string with the letter following it in the alphabet (ie. c becomes d, z becomes a). Then capitalize every vowel in this new string (a, e, i, o, u) and finally return this modified string.
function LetterChanges(str) {
str = str.trim().toLowerCase();
var len = str.length;
var newStr = '';
for (var i = 0; i < len; i++) {
if (/[a-ce-gi-mo-su-y]/.test(str[i])) {
newStr += String.fromCharCode(((str[i].charCodeAt(0) - 18) % 26) +
97)
}
else if (/[zdhnt]/.test(str[i])) {
newStr += String.fromCharCode(((str[i].charCodeAt(0) - 18) % 26) +
65);
}
else {
newStr += str[i];
}
}
return newStr;
}
LetterChanges(readline());
Fact: charCode for 'a' is 97, and (97 - 18) % 26 == 1
Take 'b' for example, (98 - 18) % 26 == 2, so after change, its charCode equals 97 + 2 == 99, becomes 'c'. This rule applies to all 'a-z'.
Now you should see the pattern.
Quiz: what if you want to change uppercase letters, what would you pick as the "magic number" for this case?
About ASCII
Well, as you know, computers don't store characters as 'a', 'b', 'z' or '.', they only accept binary bits (0 or 1). These binary bits can be used to form integers and numbers, but not strings and characters.
So how does the computer store characters? That's where ASCII (American Standard Code for Information Interchange) comes in.
So the idea is that each character needs to be stored as a number, and ASCII code is then the standardization for what number corresponds to what character and vice versa.
So to answer your first question: String.fromCharCode(x) is just returning you the character in the standardized ASCII table corresponding to the number x. For eg, String.fromCharCode(65) will return you 'A' because the ASCII code for 'A' is standardized by the standard as 65.
Why -18
It's a clever (but confusing) hack to force all the lowercase letters to the character following it.
Because str has been made to be lowercase by the line str = str.trim().toLowerCase();, str[i] will now only contain values from 97 ('a') to 97+25 = 122 ('z').
Now 18 = 122 (mod 26) or 122%26.
This is necessary to accommodate for the fact that 'z' needs to go to 'a', and since we only have 26 characters from 'a' to 'z' that we need to "wrap around" (modulus/%)
Note that:
(97('a')-18)%26 = 1
(98('b')-18)%26 = 2
...
(122('z')-18)%26 = 0
So when you add 97 ('a') to each of the numbers you get a function mapping of 'a'->'b', 'b'->'c', ... , 'z'->'a'

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.
function dec2bin(dec) {
return (dec >>> 0).toString(2);
}
console.log(dec2bin(1)); // 1
console.log(dec2bin(-1)); // 11111111111111111111111111111111
console.log(dec2bin(256)); // 100000000
console.log(dec2bin(-256)); // 11111111111111111111111100000000
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.
Try
num.toString(2);
The 2 is the radix and can be any base between 2 and 36
source here
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:
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);
}
}
I had some help from here
A simple way is just...
Number(42).toString(2);
// "101010"
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.
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"
This answer attempts to address inputs with an absolute value in the range of 214748364810 (231) – 900719925474099110 (253-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 (-231) – 214748364710 (231-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:
function toBinary (value) {
if (!Number.isSafeInteger(value)) {
throw new TypeError('value must be a safe integer');
}
const negative = value < 0;
const twosComplement = negative ? Number.MAX_SAFE_INTEGER + value + 1 : value;
const signExtend = negative ? '1' : '0';
return twosComplement.toString(2).padStart(53, '0').padStart(64, signExtend);
}
function format (value) {
console.log(value.toString().padStart(64));
console.log(value.toString(2).padStart(64));
console.log(toBinary(value));
}
format(8);
format(-8);
format(2**33-1);
format(-(2**33-1));
format(2**53-1);
format(-(2**53-1));
format(2**52);
format(-(2**52));
format(2**52+1);
format(-(2**52+1));
.as-console-wrapper{max-height:100%!important}
For older browsers, polyfills exist for the following functions and values:
Number.isSafeInteger()
Number.isInteger()
Number.MAX_SAFE_INTEGER
String.prototype.padStart()
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:
function toRadix (value, radix) {
if (!Number.isSafeInteger(value)) {
throw new TypeError('value must be a safe integer');
}
const digits = Math.ceil(64 / Math.log2(radix));
const twosComplement = value < 0
? BigInt(radix) ** BigInt(digits) + BigInt(value)
: value;
return twosComplement.toString(radix).padStart(digits, '0');
}
console.log(toRadix(0xcba9876543210, 2));
console.log(toRadix(-0xcba9876543210, 2));
console.log(toRadix(0xcba9876543210, 16));
console.log(toRadix(-0xcba9876543210, 16));
console.log(toRadix(0x1032547698bac, 2));
console.log(toRadix(-0x1032547698bac, 2));
console.log(toRadix(0x1032547698bac, 16));
console.log(toRadix(-0x1032547698bac, 16));
.as-console-wrapper{max-height:100%!important}
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
Note- the old link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators now redirects elsewhere and doesn't have that content but the proper old link , which comes up when archive.org retrieves pages!, is available here https://web.archive.org/web/20150315015832/https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators
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.
https://web.archive.org/web/20150315015832/https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators
function createBinaryString(nMask) {
// nMask must be between -2147483648 and 2147483647
if (nMask > 2**31-1)
throw "number too large. number shouldn't be > 2**31-1"; //added
if (nMask < -1*(2**31))
throw "number too far negative, number shouldn't be < -(2**31)" //added
for (var nFlag = 0, nShifted = nMask, sMask = ''; nFlag < 32;
nFlag++, sMask += String(nShifted >>> 31), nShifted <<= 1);
sMask=sMask.replace(/\B(?=(.{8})+(?!.))/g, " ") // added
return sMask;
}
console.log(createBinaryString(-1)) // "11111111 11111111 11111111 11111111"
console.log(createBinaryString(1024)) // "00000000 00000000 00000100 00000000"
console.log(createBinaryString(-2)) // "11111111 11111111 11111111 11111110"
console.log(createBinaryString(-1024)) // "11111111 11111111 11111100 00000000"
//added further console.log example
console.log(createBinaryString(2**31 -1)) //"01111111 11111111 11111111 11111111"
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
~ | 1 |~
example of above line: 2 * 4 = 8 and remainder is 1
so 9 = 1 0 0 1
function numToBit(num){
var number = num
var result = []
while(number >= 1 ){
result.unshift(Math.floor(number%2))
number = number/2
}
return result
}
Read remainders from bottom to top. Digit 1 in the middle to top.
This is how I manage to handle it:
const decbin = nbr => {
if(nbr < 0){
nbr = 0xFFFFFFFF + nbr + 1
}
return parseInt(nbr, 10).toString(2)
};
got it from this link: https://locutus.io/php/math/decbin/
we can also calculate the binary for positive or negative numbers as below:
function toBinary(n){
let binary = "";
if (n < 0) {
n = n >>> 0;
}
while(Math.ceil(n/2) > 0){
binary = n%2 + binary;
n = Math.floor(n/2);
}
return binary;
}
console.log(toBinary(7));
console.log(toBinary(-7));
You could use a recursive solution:
function intToBinary(number, res = "") {
if (number < 1)
if (res === "") return "0"
else
return res
else return intToBinary(Math.floor(number / 2), number % 2 + res)
}
console.log(intToBinary(12))
console.log(intToBinary(546))
console.log(intToBinary(0))
console.log(intToBinary(125))
Works only with positive numbers.
An actual solution that logic can be implemented by any programming language:
If you sure it is positive only:
var a = 0;
var n = 12; // your input
var m = 1;
while(n) {
a = a + n%2*m;
n = Math.floor(n/2);
m = m*10;
}
console.log(n, ':', a) // 12 : 1100
If can negative or positive -
(n >>> 0).toString(2)
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 0s to the left while negative numbers will add 1s. 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.
Here we have a working snippet of these algos:
function dec2binA(n) {
if (!Number.isSafeInteger(n)) throw new TypeError('n value must be a safe integer')
if (n > 2**31) throw 'number too large. number should not be greater than 2**31'
if (n < -1*(2**31)) throw 'number too far negative, number should not be lesser than 2**31'
const bin = n < 0 ? Number.MAX_SAFE_INTEGER + 1 + n : n
const signBit = n < 0 ? '1' : '0'
return parseInt(bin, 10).toString(2)
.padStart(56, signBit)
.replace(/\B(?=(.{8})+(?!.))/g, ' ')
}
function dec2binB(n) {
if (!Number.isSafeInteger(n)) throw new TypeError('n value must be a safe integer')
if (n > 2**31) throw 'number too large. number should not be greater than 2**31'
if (n < -1*(2**31)) throw 'number too far negative, number should not be lesser than 2**31'
const bin = n < 0 ? -(1 + n) : n
const signBit = n < 0 ? '1' : '0'
return parseInt(bin, 10).toString(2)
.replace(/[01]/g, d => +!+d)
.padStart(56, signBit)
.replace(/\B(?=(.{8})+(?!.))/g, ' ')
}
const a = -805306368
console.log(a)
console.log('dec2binA:', dec2binA(a))
console.log('dec2binB:', dec2binB(a))
const b = -3
console.log(b)
console.log('dec2binA:', dec2binA(b))
console.log('dec2binB:', dec2binB(b))
One more alternative
const decToBin = dec => {
let bin = '';
let f = false;
while (!f) {
bin = bin + (dec % 2);
dec = Math.trunc(dec / 2);
if (dec === 0 ) f = true;
}
return bin.split("").reverse().join("");
}
console.log(decToBin(0));
console.log(decToBin(1));
console.log(decToBin(2));
console.log(decToBin(3));
console.log(decToBin(4));
console.log(decToBin(5));
console.log(decToBin(6));
I used a different approach to come up with something that does this. I've decided to not use this code in my project, but I thought I'd leave it somewhere relevant in case it is useful for someone.
Doesn't use bit-shifting or two's complement coercion.
You choose the number of bits that comes out (it checks for valid values of '8', '16', '32', but I suppose you could change that)
You choose whether to treat it as a signed or unsigned integer.
It will check for range issues given the combination of signed/unsigned and number of bits, though you'll want to improve the error handling.
It also has the "reverse" version of the function which converts the bits back to the int. You'll need that since there's probably nothing else that will interpret this output :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("---");
This is a method that I use. It's a very fast and concise method that works for whole numbers.
If you want, this method also works with BigInts. You just have to change each 1 to 1n.
// Assuming {num} is a whole number
function toBin(num){
let str = "";
do {
str = `${num & 1}${str}`;
num >>= 1;
} while(num);
return str
}
Explanation
This method, in a way, goes through all the bits of the number as if it's already a binary number.
It starts with an empty string, and then it prepends the last bit. num & 1 will return the last bit of the number (1 or 0). num >>= 1 then removes the last bit and makes the second-to-last bit the new last bit. The process is repeated until all the bits have been read.
Of course, this is an extreme simplification of what's actually going on. But this is how I generalize it.
This is my code:
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();
This is the solution . Its quite simple as a matter of fact
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.
*/

Categories

Resources