js十进制与十六进制互相转换(含负数)

/**
 * 十进制(含负数)整数转十六进制
 * @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
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值