简体   繁体   English

2的补码-如果需要再用一位表示2的补码形式的二进制数怎么办

[英]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: 我知道如何将带符号的整数转换为其等效的二进制补码,但这是我的困惑:

  1. I've done some research and people say the op-code which is the carry-bit tells the CPU if a 2's complement code represents a positive integer or a negative, but sometimes the carry-bit is ignored according to some people; 我已经做过一些研究,有人说操作码是进位,它告诉CPU 2的补码表示正整数还是负数,但是有些人有时会忽略进位。 for instance, adding 1111 (-1) to 1000 (-8) you get 10111 (-9), but if it's a 4-bit computer, the most significant bit which is the 5th bit cannot be stored, so how does the computer deal with that ? 例如,将1111(-1)加到1000(-8)会得到10111(-9),但是如果它是4位计算机,那么最高有效位(即第5位)就无法存储,那么计算机该如何存储处理那个?
  2. A somewhat trivial question is if it's given that 00110011 represent a signed integer in two's complement form, how do I know if the actual code is 0110011, which is a positive number (in 2's complement form), or 110011, which is a negative number (in 2's complement form) ? 一个比较琐碎的问题是,是否给定00110011以二进制补码形式表示一个有符号整数,我如何知道实际代码是0110011(是一个正数(以2的补码形式)还是110011,它是一个负数) (以2的补码形式)?

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM