/**
* 十进制(含负数)整数转十六进制
* @param decimalNumber
* @param byteLen
* @returns {string}
*/
function decimal2hex(decimalNumber, byteLen) { // byteLen:字节长度,可选值:2,4
if (decimalNumber >= 0) {
return decimalNumber.toString(16).toUpperCase().padStart(byteLen * 2, '0');
}
// Compute the two's complement
const twosComplement = (Math.pow(2, byteLen * 8) + decimalNumber) >>> 0;
// Convert to hexadecimal
return twosComplement.toString(16).toUpperCase().padStart(byteLen * 2, '0');
}
/**
* 十六进制(含负数)整数转十进制
* @param hexString
* @param byteLen
* @returns {number}
*/
function hex2decimal(hexString, byteLen) {
let decimalNumber = parseInt(hexString, 16);
// Check if the most significant bit is set (indicating a negative number)
const MSB = 1 << (byteLen * 8 - 1);
const isHexadecimalNegative = (decimalNumber & MSB) !== 0;
if (!isHexadecimalNegative) {
return decimalNumber
}
if (decimalNumber & MSB) {
// Convert to binary representation
let binaryString = decimalNumber.toString(2);
binaryString = binaryString.padStart(hexString.length * 4, '0'); // Ensure proper length
// Take two's complement to get the negative binary representation
let negBinaryString = '';
for (let i = 0; i < binaryString.length; i++) {
negBinaryString += binaryString[i] === '0' ? '1' : '0';
}
// Add 1 to complete two's complement representation
decimalNumber = -(parseInt(negBinaryString, 2) + 1);
}
return decimalNumber;
}
const byteLen = 4;
const a = -20130;
const b = decimal2hex(a, byteLen);
console.log(b, hex2decimal(b, byteLen)) // FFFFB15E -20130
11-11
1173
10-24
2万+
05-22
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交