我需要通过两个补码符号将一个有符号的整数编码为十六进制。例如,我想转换
e.g. -24375 to 0xffffa0c9.
到目前为止,我一直在做以下工作:
parseInt(-24375).toString(2)
> "-101111100110111"
这与Wolfram displays匹配,但我不知道如何获得数字的24位int表示(ffffa0c9)。
我已经想出了如何取无符号二进制数,并将其表示为2的补码:
~ parseInt("101111100110111", 2) + 1
> -23475
但我不确定要将这个数字的二进制表示转换为十六进制。
有什么想法吗?
发布于 2019-03-24 18:03:34
为了创建两个固定大小的称赞号,我创建了工厂方法:
function createToInt(size) {
if (size < 2) {
throw new Error('Minimum size is 2');
}
else if (size > 64) {
throw new Error('Maximum size is 64');
}
// Determine value range
const maxValue = (1 << (size - 1)) - 1;
const minValue = -maxValue - 1;
return (value) => {
if (value > maxValue || value < minValue) {
throw new Error(`Int${size} overflow`);
}
if (value < 0) {
return (1 << size) + value;
}
else {
return value;
}
};
}
现在,为了解决您的问题,您可以创建函数toInt8
、toInt16
、toInt32
等,并使用它将JS数字转换为二次恭维。使用int8的示例:
const toInt8 = createToInt(8);
'0x' + toInt8(-128).toString(16); // -> 0x80
'0x' + toInt8(127).toString(16); // -> 0x7f
'0x' + toInt8(-1).toString(16); // -> 0xff
// Values less then 16 should be padded
'0x' + toInt8(10).toString(16).padStart(2, '0); // -> 0x0a
发布于 2020-08-14 05:20:47
下面是一个非常简单的使用parseInt
的解决方案:
function DecimalHexTwosComplement(decimal) {
var size = 8;
if (decimal >= 0) {
var hexadecimal = decimal.toString(16);
while ((hexadecimal.length % size) != 0) {
hexadecimal = "" + 0 + hexadecimal;
}
return hexadecimal;
} else {
var hexadecimal = Math.abs(decimal).toString(16);
while ((hexadecimal.length % size) != 0) {
hexadecimal = "" + 0 + hexadecimal;
}
var output = '';
for (i = 0; i < hexadecimal.length; i++) {
output += (0x0F - parseInt(hexadecimal[i], 16)).toString(16);
}
output = (0x01 + parseInt(output, 16)).toString(16);
return output;
}
}
对于长度不超过16的十六进制来说,应该工作得很好。
https://stackoverflow.com/questions/6146177
复制