C中没有减号的减法 [英] Subtraction without minus sign in C
问题描述
如何在没有-
运算符的情况下在C中减去两个整数?
How can I subtract two integers in C without the -
operator?
推荐答案
int a = 34;
int b = 50;
您可以使用取反并加1将b转换为负值.
You can convert b to negative value using negation and adding 1:
int c = a + (~b + 1);
printf("%d\n", c);
-16
这是二进制补码负号.当您要否定值或对其进行子跟踪时,如果您使用'-'运算符,则处理器正在执行此操作.
This is two's complement sign negation. Processor is doing it when you use '-' operator when you want to negate value or subtrackt it.
转换浮点数更简单.只需否定第一位(shoosh为您提供了如何执行此操作的示例).
Converting float is simpler. Just negate first bit (shoosh gave you example how to do this).
好的,伙计们.我放弃.这是我的独立于编译器的版本:
Ok, guys. I give up. Here is my compiler independent version:
#include <stdio.h>
unsigned int adder(unsigned int a, unsigned int b) {
unsigned int loop = 1;
unsigned int sum = 0;
unsigned int ai, bi, ci;
while (loop) {
ai = a & loop;
bi = b & loop;
ci = sum & loop;
sum = sum ^ ai ^ bi; // add i-th bit of a and b, and add carry bit stored in sum i-th bit
loop = loop << 1;
if ((ai&bi)|(ci&ai)|(ci&bi)) sum = sum^loop; // add carry bit
}
return sum;
}
unsigned int sub(unsigned int a, unsigned int b) {
return adder(a, adder(~b, 1)); // add negation + 1 (two's complement here)
}
int main() {
unsigned int a = 35;
unsigned int b = 40;
printf("%u - %u = %d\n", a, b, sub(a, b)); // printf function isn't compiler independent here
return 0;
}
我正在使用unsigned int,以便任何编译器都将其视为相同.
I'm using unsigned int so that any compiler will treat it the same.
如果要减去负值,则可以这样做:
If you want to subtract negative values, then do it that way:
unsgined int negative15 = adder(~15, 1);
现在,我们完全独立于有符号值的约定.在我的方法中,所有整数都将被存储为二进制补码-因此,对于较大的整数(必须从0位开始),您必须要小心.
Now we are completly independent of signed values conventions. In my approach result all ints will be stored as two's complement - so you have to be careful with bigger ints (they have to start with 0 bit).
这篇关于C中没有减号的减法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!