为了加强对原码,反码,补码的理解,写了一个js函数整型转原码二进制的函数,同时支持反码和补码
- 原码就是符号位加上真值的绝对值
- 反码是正数的反码是其本身;负数的反码是在其原码的基础上,符号位不变,其余各个位取反
- 补码是正数的补码就是其本身;负数的补码是在其原码的基础上,符号位不变,其余各位取反,最后+1。(也即在反码的基础上+1)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| const int_to_binary = (num, size, type) => { size = size || 64; type = type || 0; const negative = num < 0; const reverseAndNegative = type === 1 && negative; const arr = new Array(size).fill(reverseAndNegative ? '1' : '0'); let cur = Math.abs(num); if (type === 2 && negative) { cur += 1; } let j = size - 1; while (cur !== 0) { const remainder = cur % 2; cur = (cur - remainder) / 2; if (reverseAndNegative) { arr[j] = remainder === 0 ? '1' : '0'; } else { arr[j] = remainder; } j--; if (j < 0) { throw 'overflow' } } arr[0] = negative ? '1' : '0'; return arr.join(''); }; console.log(int_to_binary( 123, 16, 0)) console.log(int_to_binary(-123, 16, 0)) console.log(int_to_binary( 123, 16, 1)) console.log(int_to_binary(-123, 16, 1)) console.log(int_to_binary( 123, 16, 2)) console.log(int_to_binary(-123, 16, 2))
|