[英]two's complement - what if there's one more bit needed to represent a binary in 2's complement form
I'm doing computer science A-level course in a high school and currently working on two's complement arithmetic. 我在一所高中正在学习计算机科学A级课程,并且目前正在从事补数算法的研究。 For some reason I don't quite get it. 由于某种原因,我不太了解。 I know how to convert a signed integer into its two's complement equivalent, but here're my confusions: 我知道如何将带符号的整数转换为其等效的二进制补码,但这是我的困惑:
Thanks! 谢谢!
Typically, what doesn't fit is lost. 通常,不适合的东西会丢失。 So, 1111 2 + 1000 2 = 0111 2 . 因此,1111 2 + 1000 2 = 0111 2 。 However, some CPUs have special flags which get set to 0 or 1 depending on whether or not there's unsigned overflow (the carry flag) and signed overflow (the overflow flag). 但是,某些CPU具有特殊标志,这些标志根据是否存在无符号溢出(进位标志)和有符号溢出(溢出标志)而设置为0或1。 Some CPUs may be able to automatically raise an overflow exception when an arithmetic instruction can't produce result without overflow. 当算术指令没有溢出就无法产生结果时,某些CPU可能能够自动引发溢出异常。
Typically, the CPU does not care if 1111 2 is -1 10 or 15 10 . 通常,CPU不在乎1111 2是-1 10还是15 10 。 Binary addition and subtraction of two N-bit integers gives you the same N-bit sum or difference irrespective of whether you're operating on unsigned integers or 2's complement signed integers. 不管您是对无符号整数还是对2的补码有符号整数进行操作,两个N位整数的二进制加法和减法都会为您提供相同的N位总和或差。 The same is true when multiplying two N-bit signed 2's complement or unsigned integers: the N least significant bits of the product is the same in both cases. 将两个N位带符号的2的补码或无符号整数相乘时,情况也是如此:两种情况下,乘积的N个最低有效位相同。
IOW, it's your job to keep track of what types you're manipulating, to take care of overflows (if they're possible) and to select proper instructions for those types (eg you typically have signed and unsigned division, signed and unsigned comparison, etc). IOW,您的工作就是要跟踪要处理的类型,照顾溢出(如果可能的话),并为这些类型选择适当的指令(例如,您通常有带符号和无符号除法,带符号和无符号比较)等)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.