简体   繁体   中英

Javascript: A byte is supposed to be 8 bits

EDIT: http://www.ascii-code.com/ I see the BIN column as binary but I am clearly missing something..

Why doesn't binary conversion work for me?

Lowercase b is character code 98

console.log((98).toString(2));

outputs

1100010

The length of the output is 7 when it should be 8

A byte is 8 bits!!?

EDIT

Groups of Bits make up a Byte When 8 bits are grouped together, it is then known as a byte. And bytes are what computers use to represent various characters such as those you see on your keyboard.

Quoted from: http://wordsmuggler.com/Learn/Binary

I really don't understand now what I am supposed to read. If I look on Google I always am told 8 but here I am told different. Please explain as I don't understand what I am supposed to be understanding

The reason why .toString(2) does not produce an 8-bit representation of a number is that toString works for more numbers than just 0 through 255. For example:

(1).toString(2) ==> "1"
(2).toString(2) ==> "10"
(3).toString(2) ==> "11"
(4).toString(2) ==> "100"
(25).toString(2) ==> "11001"
(934534534).toString(2) => "110111101100111101110110000110"

So what JavaScript is doing with toString(2) is simply giving you numbers in base 2, namely 0, 1, 10, 11, 100, 101, etc., the same way that in base 10 we write our numbers 0, 1, 2, 3, 4, 5, ... and we don't always pad out our numbers to make a certain number of digits. That is why you are not seeing 8 binary digits in your output.

Now, the problem you have in mind is "how do I take a number in the range 0..255 and show it as a binary-encoded BYTE in JavaScript? It turns out that needs to be done by the programmer; it is not a built-in operation in JavaScript! Writing a number in base-2, and writing an 8-bit, are related problems, but they are different.

To do what you would like to, you can write a function:

function byteString(n) {
  if (n < 0 || n > 255 || n % 1 !== 0) {
      throw new Error(n + " does not fit in a byte");
  }
  return ("000000000" + n.toString(2)).substr(-8)
}

Here is how it can be used:

> byteString(-4)
Error: -4 does not fit in a byte
> byteString(0)
'00000000'
> byteString(7)
'00000111'
> byteString(255)
'11111111'
> byteString(256)
Error: 256 does not fit in a byte

Here is another solution :

test = "11001";
while(test.length<7){
  test="0"+test;
}

It works in a single line just like that :

while(test.length<7)test="0"+test

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM