In the 32-bit environment, design a 32-bit unsigned long integer summation function, added to and stored in a two 32-bit unsigned integer

Source: Internet
Author: User
In the 32-bit environment, use C to design a 32-bit unsigned long integer summation function that is stored in two 32-bit unsigned integers.
function interface is defined as

void Add64 (unsigned int add1, unsigned int add2, unsigned int* psumhigh, unsigned int*)

Please give the implementation code of the function.


This can be done without the 64-bit type:

C + + code

 
 void Add64 (unsigned int add1, unsigned int add2, unsigned int* psumhigh, unsigned int* psumlow) 
 { 
 	*psumlow = add1; 
 	*psumhigh = 0; 
  
 	unsigned int i = 0; 
  
 	Do  
 	{ 
 		if (++*psumlow = = 0) 
 		{ 
 			++*psumhigh 
 		} 
  
 	} while (++i  < ADD2); 
 } 
  
 int _tmain (int argc, _tchar* argv[]) 
 { 
 	unsigned int h, l; 
  
 	Add64 (0xffffff00, 0x000000ff, &h, &l);	0x00000000, 0xFFFFFFFF 
 	Add64 (0xFFFFFFFF, 0x00000001, &h, &l);	0x00000001, 0x00000000 
 	Add64 (0xFFFFFFFF, 0x00000003, &h, &l);	0x00000001, 0x00000002 return 
  
 	0; 
 } 
  
 


The above actually writes the complexity, this idea uses in multiplication's more reasonable.

In addition, the maximum value of this sumhigh may be 1, that is, if it were not 0, but 1, this could be done by determining whether there is an overflow, two unsigned integers added, and the overflow is equivalent to and less than one addends (if the register identifier bit is not to be judged). Well, you can do this:
C + + code
void Add64 (unsigned int add1, unsigned int add2, unsigned int * psumhigh, unsigned int * psumlow) {* Psumlow = add1 + add 2; if (* Psumlow < ADD1 | | * Psumhigh < ADD2) {* Psumhigh = 1;} else {* Psumhigh = 0;}} int _tmain (int argc, _TCHAR * argv[]) {unsigned int h, l; Add64 (0xffffff00, 0X000000FF, & H, & L); 0x00000000, 0xFFFFFFFF Add64 (0xFFFFFFFF, 0x00000001, & H, & L); 0x00000001, 0x00000000 Add64 (0xFFFFFFFF, 0x00000003, & H, & L); 0x00000001, 0x00000002 return 0; }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.