0

I have a value that is integral form, but I don't know if it is Uint8 or Uint16 or Uint32. Now I want to get byte size of it for example I want some thing like this:

var a = 100;     // 1100100
var b = 1000;    // 1111101000
console.log (byteSizeOf(a)); // --> 2
console.log (byteSizeOf(b)); // --> 3

Anyone can help me?

pouyan
  • 3,445
  • 4
  • 26
  • 44
  • have you tried https://github.com/inexorabletash/text-encoding ? – Majid Oct 09 '16 at 08:49
  • its's (signed) int32, that's an "optimization" that you can rely on nowadays, afaik. the spec defines all numbers in JS as doubles (64Bit floating point values) – Thomas Oct 09 '16 at 08:50

1 Answers1

0

You can use basic math, if thats only decimal numbers you need to size:

Math.ceil(Math.log2(100)/4) 

--> 2

Math.ceil(Math.log2(1000)/4) 

--> 3

But you also have to handle spacial case of 0 and 1:

function byteSizeOf( x ) {
    return ( x < 2 )?1:Math.ceil(Math.log2(x)/4);
}

You can convert number to binary string like here: how do I convert an integer to binary in javascript?

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

And then you can convert the result to binary array:

"110011".split().map(function(x){return parseInt(x);})
Community
  • 1
  • 1
Vladimir M
  • 4,403
  • 1
  • 19
  • 24
  • tanks for your answer but is it possible to get its binary data too? for example for 100 get '1100100'. – pouyan Oct 09 '16 at 09:02
  • i meant that we send 100 to function and it returns 1100100. and also not string( it should be number) – pouyan Oct 09 '16 at 09:19
  • a number? js does not have binary numbers, so 1100100 will be interpreted as decimal. Meaning that it has to be represented as string. – Vladimir M Oct 09 '16 at 09:22
  • no. in fact i mean binary array. sorry that i didn't mentioned it.like array buffer – pouyan Oct 09 '16 at 09:23