简体   繁体   中英

2's complement binary expected output

I'm studying for my exam, and I would like to check my answers to this question:

Suppose binary values are signed 8-bit values, representing twos-complement format with a decimal range from -128 to 127. Which of the following statements are true/false?

1) 11111111 > 0111111

I think this is false because the first digit represents the sign, so we're comparing a negative value to a positive value.

2) (11111111 + 11111111) > (00000001 - 00000010)

I'm not so sure about this one because I don't know what happens when it overflows. I think the computer just drops the last digit. So I think the left-hand side is like -128 - 128 = -256. Then the right-hand side is 1 - 2 = -1, which is represented as 1000001. This means the inequality, in decimal, becomes -256 > -1, which is false. But again, I am not so sure about this one.

3) (10000000 / 00000100) == 11100000

The first part is -0/4 and the second part is non-zero, so would it be false?


Also, there are only sample problems, and I would like to practice/explore on my own. Is there any way in which I can write a C++ program to see the expected output of questions of this form?

Thank you.

Regarding playing around with this in C++, there are a bunch of bit manipulation libraries out there (just searching for "C++ bit manipulation library" will turn up lots of results). As a few examples:

  1. https://github.com/Chris--A/BitBool
  2. https://www.slac.stanford.edu/comp/unix/gnu-info/libg++_23.html

You may or may not find one that has a built-in notion of two's complement. Regardless, it could be a useful exercise for yourself to implement that kind of functionality on top of what one of these libraries provides, for example by subclassing something they provide or writing your own class encapsulating an existing library implementation as a data member.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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