Click here to Skip to main content
15,886,362 members
Articles / Programming Languages / C++

Scaling 64 bit integers

Rate me:
Please Sign up or sign in to vote.
4.36/5 (12 votes)
22 Feb 20054 min read 66K   1.2K   20  
An article on scaling 64 bit integers using extended precision integer arithmetic.
//
// TestMulDiv64.cpp : Defines the entry point for the console application.
//
// This is a small test program that shows the use of MulDiv64.
// You can run it to see the three calculated results.
// The first result should be 0x0000000000000001, which is clearly wrong.
// The second result is 0x38E38E38E38E38E2, which is the correct result.
// The third result is the same as the second showing that for certain 
// denominators the faster MulShr64 can be used.
//
// Author: Richard van der Wal
// e-Mail: R.vdWal@xs4all.nl
//

#include "stdafx.h"
#include "..\MulDiv64.h"


// For printing the 64-bit values to the console
union{
	__int64 qword;
	DWORD	dword[2];
} rep;


// The program starts here
int _tmain(int argc, _TCHAR* argv[])
{
	__int64 r = 0;
	__int64 a = 0xaaaaaaaaaaaaaaaa;
	__int64 b = 0x5555555555555555;
	__int64 c = 0x1000000000000000;	// = 1 shl 60
	char s = 60;
	
	// This will return an incorrect result
	r = a * b / c;

	rep.qword = r;
	printf("Plain result: \t\t%08X %08X\n", rep.dword[1], rep.dword[0]);
	
	// This will return the correct result
	r = MulDiv64(a, b, c);

	rep.qword = r;
	printf("MulDiv64 result: \t%08X %08X\n", rep.dword[1], rep.dword[0]);
	
	// Because dividing by c can be expressed as a right shift
	// we can obtain the correct scaling faster with:
	r = MulShr64(a, b, s);

	rep.qword = r;
	printf("MulShr64 result: \t%08X %08X\n", rep.dword[1], rep.dword[0]);
	
	return 0;
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Software Developer (Senior)
Netherlands Netherlands
Richard van der Wal is a Software Development Engineer at Fugro Intersite B.V.
He holds a bachelors in mechanical engineering and a bachelors in information technology and had many years of experience in industrial automation before he started his job at Intersite. His current activities focus on software design and system design for real-time data processing in the offshore industry both on Windows PCs and embedded Linux platforms.

Comments and Discussions