How can I subtract two integers in C without the - operator?
How can I subtract two integers in C without the – operator?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You can convert b to negative value using negation and adding 1:
This is two’s complement sign negation. Processor is doing it when you use ‘-‘ operator when you want to negate value or subtrackt it.
Converting float is simpler. Just negate first bit (shoosh gave you example how to do this).
EDIT:
Ok, guys. I give up. Here is my compiler independent version:
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:
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).