25

I was asked to convert the integers to 32-bit binary numbers. So is used integer.toString(2) and got the required value in 32-bit binary format of 0'sand 1's. But actually what I was asked to do is convert the integer into 4 bytes of data. I am unable to get the output as suggested. I have used integer.toString(8), integer.toString(16). but of no use.

Example:

 num=1065489844 
 num.toString(2) //Output: 111111100000100001010110110100
 num.toString(8) //Output: 7740412664

Please let me know, where I am lacking.

4
  • 3
    Strings are not generally the same as binary data. If you could use a base of 256 they would be the same, but toString() only supports bases up to 36. Commented Apr 2, 2013 at 10:30
  • 3
    What do you want the output to be? It is not clear what the intended 4 bytes output should look like? Commented Apr 2, 2013 at 10:32
  • 1
    Say your integer is stored in a variable x. Then using x | 0 will ensure that it's a 32-bit integer. I've no idea what you mean by "binary number". Every integer in every programming language is stored as bits. Commented Apr 2, 2013 at 10:34
  • 1
    32 bits IS 4 bytes. you are already done. Commented Jun 28, 2020 at 20:55

3 Answers 3

39

Now you can use ArrayBuffer and DataView. They are native so the performance will be much better if you need to use it very often.

function toBytesInt32 (num) {
    arr = new ArrayBuffer(4); // an Int32 takes 4 bytes
    view = new DataView(arr);
    view.setUint32(0, num, false); // byteOffset = 0; litteEndian = false
    return arr;
}

equals to

function toBytesInt32 (num) {
    arr = new Uint8Array([
         (num & 0xff000000) >> 24,
         (num & 0x00ff0000) >> 16,
         (num & 0x0000ff00) >> 8,
         (num & 0x000000ff)
    ]);
    return arr.buffer;
}

which use javascript bitwise operators to achieve that.

Sign up to request clarification or add additional context in comments.

2 Comments

It is actually pretty interesting to see why (uint8) (num & 0xFF000000) >> 24 works for e.g. num = 0xF0000000: The >> operator converts its operands to 32-bit two-complements, thus 0xF0000000 overflows to -0x0FFFFFFF which is shifted to -0x0F. The Uint8Array then converts its values to unsigned 8-bit integers by taking -0x0F modulo 0xFF (this modulo here is NOT the % operator but always returns positive results according to the JS specs). The result of that is finally 0xF0, as expected. Would be a nice interview question ;)
@le_m You may want to revisit your comment. Conversion to 32-bit numbers happens immediately at &, not just at >>. After & and >> the number is -16 or -0x10; not -0x0F. You can do without the mental gymnastics, if you look at the intermediate results just like the operators do: Think of bitstrings instead of numbers.
5

SEIAROTg's answer does not output a string. I have theroughly tested with both positive and negative numbers and this code will give you a 4 byte string output representing the number in big endien format(2's compliment 0xFFFFFFFF = -1).

var toBytesInt32=function(num) {
    var ascii='';
    for (let i=3;i>=0;i--) {
        ascii+=String.fromCharCode((num>>(8*i))&255);
    }
    return ascii;
};

by the way if you want to go the other way around you can use

var fromBytesInt32=function(numString) {
    var result=0;
    for (let i=3;i>=0;i--) {
        result+=numString.charCodeAt(3-i)<<(8*i);
    }
    return result;
};

to convert a 4 byte string to an integer

3 Comments

That's a javascript limitation. Javascript considers any 32 bit number with the first digit as 1 a negative number.
I made a wrong assumption about your code. Your answer is working fine for negative and positive arguments as long as they are in the range of (signed) 32 bit integers. I will delete my comments, sorry for the confusion
+1, perfect for storing a signed 32 bit int if space-efficiency is paramount. I'm using this in Google Apps Script to save lots of CRC-32 checksums with limited storage (500 kB per user storage, keys and values must be strings). btw: I just tested both functions for the whole int32 range (from -2^31 to 2^31 - 1), worked perfectly.
3

if you need a hex format output, here is the code.

/* Convert value as 8-bit unsigned integer to 2 digit hexadecimal number. */

function hex8(val) {
    val &= 0xFF;
    var hex = val.toString(16).toUpperCase();
    return ("00" + hex).slice(-2);
}

/* Convert value as 16-bit unsigned integer to 4 digit hexadecimal number. */

function hex16(val) {
    val &= 0xFFFF;
    var hex = val.toString(16).toUpperCase();
    return ("0000" + hex).slice(-4);
}

/* Convert value as 32-bit unsigned integer to 8 digit hexadecimal number. */

function hex32(val) {
    val &= 0xFFFFFFFF;
    var hex = val.toString(16).toUpperCase();
    return ("00000000" + hex).slice(-8);
}


var num = 1065489844;
console.log("0x" + hex32(num)); // will output 0x3F8215B4 

5 Comments

What I did is, I have used num.tostring(2) and sent the value to a text file, and after observation, I found that the size of text file is 32bytes, but not 4 bytes. So as mentioned by @unwind I need to use base of 256. Please can anyone tell me , how to use base of 256 to get actual binary number.
You need to save your data as binary (not as ASCII), so the file size will be 4 Bytes.
The following code allows you to download a file which contain your num in a binary format. The size of the file will be 4 Bytes. ` function generateData(num) { var data = new Uint8Array(4); for (var i = 0; i < 4; i++) { data[i] = (num >> (i * 8)) & 0xff; } var blob = new Blob([data], { type : 'Application/octet-stream' }); return window.URL.createObjectURL(blob); } var num = 1065489844; document.write('<a href="' + generateData(num) + '" download="file.dat">download</a>');`
The file should contain the binary number and the size of that file should be 4 bytes. The size of file is set to 4 bytes but I cant see the value in it.
You can use hexedit to see the content of your file in binary mode. In javascript, using the fileReader API, you can open the file as binary content and then you can handle its content. For more about the fileReader API, here a tutorial (html5rocks.com/en/tutorials/file/dndfiles/#toc-reading-files)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.