I have a binary string like "11100011" and I want to convert it into a byte. I have a working example in Java like below:
byte b1 = (byte)Integer.parseInt("11100011", 2);
System.out.println(b1);
Run Code Online (Sandbox Code Playgroud)
Here the output will be -29. But if I write some similar code in JavaScript like below:
parseInt('11100011', 2);
Run Code Online (Sandbox Code Playgroud)
I get an output of 227.
What JavaScript code I should write to get the same output as Java?
小智 5
Java 将 解释byte为有符号的二进制补码,因为最高位是 1,所以它是负数。Javascript 将它解释为无符号数,所以它总是正数。
尝试这个:
var b1 = parseInt('11100011', 2);
if(b1 > 127) b1 -= 256;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3287 次 |
| 最近记录: |