Can anyone share concept/program in C to add two 64-bit numbers on a 32-bit machine

Dani AI

Generated

Two practical options for : use your compiler's built-in 64-bit integer type when available (as suggested), or store the 64-bit value as two 32-bit halves and do a manual add-with-carry (this is the concrete form of 's "carry" idea). 's post shows a low-level masking approach; the same result can be achieved with a much shorter, easier-to-read routine.

#include <stdint.h>

typedef struct { uint32_t lo; uint32_t hi; } u64;

u64 add64(u64 a, u64 b) {
    u64 r;
    r.lo = a.lo + b.lo;
    r.hi = a.hi + b.hi + (r.lo < a.lo); /* carry if low wrapped */
    return r;
}

Notes and quick checks: use unsigned types to avoid signed overflow UB. The carry from the low half is detected by the wrap test (r.lo < a.lo). To detect a full 64-bit unsigned overflow (carry out of the high half), compare the combined result to an operand: overflow occurred if r.hi < a.hi || (r.hi == a.hi && r.lo < a.lo). Endianness does not affect arithmetic (only serialization). If your toolchain supports C99, prefer uint64_t (or unsigned long long) for simplicity and clarity; the manual method is useful when those types are unavailable or when you need to implement multiword arithmetic yourself.

Test with edge cases (e.g., add 0xFFFFFFFFFFFFFFFF + 1 => result 0, overflow/carry set) to confirm correctness on your platform.

Recommended Answers

All 4 Replies

Just use long long or __int64 data types. One of those are supported by most, if not all, modern compilers.

> Can anyone share concept
I assume you know how to add say 16 and 18 together to get 34

I mean, once you've figured out the concept of 'carry', whether you're storing each element of your overall number in a character, or byte, or long really doesn't make a bean of difference.

commented: Good to see you posting again :) +9
for(i  =  0; i < 2; i++)
{
rslt1 = ( a[i] & 0x7fffffffu ) + ( b[i] & 0x7fffffffu ) + carry;//first add 31lsb bits
carry= rslt1 >> 31;// 32 th bit is carry
rslt2 = (a[i] >> 31) + (b[i] >> 31) + carry; //add this carry with 32th bit's of operands
carry = rslt2 >> 1; //msb of answer is the carry from 32 bit addition
rslt1 = rslt1 & 0x7fffffffu;
rslt2 = rslt1 + (rslt2 << 31);//lsb of that answer is the 32th bit of original answer
result[i] = rslt2;//result stored in to an array
}

//Any doubt call me MFM india(kerala) Mob:<MOBILE NUMBER SNIPPED>

commented: cool post +1

Why all that crazy code??

__int64 a = 123;
__int64 b = 234;
__int64 c = a+b;
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.