I’m not sure why they named their parameter ‘nMask’ but i’ll leave that as is.This code takes a IEEE single-precision (32 bit) number that has been stuffed in a 32 bit unsigned integer and converts it to a floating point number. Based on How to print a number with commas as thousands separators in JavaScript (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)Īnd, 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. The code is pretty compact, a function of three lines.īut I have added a regex to format the output in groups of 8 bits. 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.Īnnan had some incorrect and unclear terminology but mentioned a solution by This works for 32-bit numbers. But rather than do that, you can go with this solution on 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. What is “2’s Complement”?Ī solution could involve prepending a 0 for positive numbers, which I did in an earlier revision of this answer. It has the output starting with 1, which for positive numbers isn’t proper 2s complement.Īnybody 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. 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.įernando mentioned a simple solution of (x>0).toString(2) which is fine for negatives, but has a slight issue when x is positive. AnswerĪ solution i’d go with that’s fine for 32-bits, is the code the end of this answer, which is from (MDN), but with some lines added for A)formatting and B)checking that the number is in range. Rather like this question, but for JavaScript. I’d like to see integers, positive or negative, in binary.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |