慕姐4208626
我用了一种不同的方法来提出这样做的东西。我决定不在我的项目中使用这个代码,但我想我会把它留在相关的地方,以防它对某人有用。不使用位移或二进制补码强制。你选择出来的位数(它检查'8','16','32'的有效值,但我想你可以改变它)您可以选择是将其视为有符号整数还是无符号整数。考虑到有符号/无符号和位数的组合,它将检查范围问题,但您需要改进错误处理。它还具有函数的“反向”版本,它将位转换回int。你需要它,因为可能没有别的东西会解释这个输出:Dfunction intToBitString(input, size, unsigned) {
if ([8, 16, 32].indexOf(size) == -1) {
throw "invalid params";
}
var min = unsigned ? 0 : - (2 ** size / 2);
var limit = unsigned ? 2 ** size : 2 ** size / 2;
if (!Number.isInteger(input) || input < min || input >= limit) {
throw "out of range or not an int";
}
if (!unsigned) {
input += limit;
}
var binary = input.toString(2).replace(/^-/, '');
return binary.padStart(size, '0');}function bitStringToInt(input, size, unsigned) {
if ([8, 16, 32].indexOf(size) == -1) {
throw "invalid params";
}
input = parseInt(input, 2);
if (!unsigned) {
input -= 2 ** size / 2;
}
return input;}// EXAMPLESvar res;console.log("(uint8)10");res = intToBitString(10, 8, true);console.log("intToBitString(res, 8, true)");console.log(res);console.log("reverse:", bitStringToInt(res, 8, true));console.log("---");console.log("(uint8)127");res = intToBitString(127, 8, true);console.log("intToBitString(res, 8, true)");console.log(res);console.log("reverse:", bitStringToInt(res, 8, true));console.log("---");console.log("(int8)127");res = intToBitString(127, 8, false);console.log("intToBitString(res, 8, false)");console.log(res);console.log("reverse:", bitStringToInt(res, 8, false));console.log("---");console.log("(int8)-128");res = intToBitString(-128, 8, false);console.log("intToBitString(res, 8, true)");console.log(res);console.log("reverse:", bitStringToInt(res, 8, true));console.log("---");console.log("(uint16)5000");res = intToBitString(5000, 16, true);console.log("intToBitString(res, 16, true)");console.log(res);console.log("reverse:", bitStringToInt(res, 16, true));console.log("---");console.log("(uint32)5000");res = intToBitString(5000, 32, true);console.log("intToBitString(res, 32, true)");console.log(res);console.log("reverse:", bitStringToInt(res, 32, true));console.log("---");