Click here to Skip to main content
12,945,401 members (81,124 online)
Click here to Skip to main content


20 bookmarked
Posted 22 Feb 2005

Scaling 64 bit integers

, 22 Feb 2005
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:

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

// For printing the 64-bit values to the console
	__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.


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


About the Author

R. van der Wal
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.

You may also be interested in...

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170518.1 | Last Updated 23 Feb 2005
Article Copyright 2005 by R. van der Wal
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid