tags:

views:

147

answers:

3

How do I add/subtract/multiply and divide integers using only 20 bits instead of 32 bits in C#?

Will these operations be faster than 32bit precision?

For example this .NET library is featuring 20 and 30 bit arithmetic with different speeds: http://complex-a5.ru/polyboolean/index.html

Thanks.

A: 

You can't, without writing your own code which will either do bit twiddling manually - or use 32 bit operations and then apply masking to limit the available range.

They certainly wouldn't be faster than 32-bit operations, as that's what the processor natively supports.

Jon Skeet
@Jon: Why this .NET library is featuring 20 and 30 bit arithmetic with different speeds? http://www.complex-a5.ru/polyboolean/index.html
devdept
@devdept: Please **update** your question to contain **all** the relevant information. Please don't add relevant facts in comments.
S.Lott
@devdept: It depends on what custom operations they're performing, which look like they're pretty specialized. It's possible that by using a 20-bit coordinate system they can get more memory efficiency in some cases. But really you'd have to ask the authors. What are *you* trying to achieve though?
Jon Skeet
@Jon: I understand the difference precision you can achieve working on 20bit or 30bit coordinate system but not why the latter should be faster using .NET... I simply trying to understand.
devdept
@devdept: All the benchmarks show 20 bit being faster than 30 bit as far as I can see.
Jon Skeet
+5  A: 

There are arithmetic units in processors so that it is really fast to do operations with 32bit numbers. It's faster than any code you can write because it is "wired" in processor.

Operations with 20bit number can be simulated with modulo arithmetic (i.e. mod 2^20).

MartyIX
+2  A: 

How do I add/subtract/multiply and divide integers using only 20 bits instead of 32 bits in C#?

Use bitmasking to zero out the top 12 bits of 32-bit ints:

int twentyBitSum = (a + b) & 0xFFFFF;

Will these operations be faster than 32bit procision?

No. Doing arithmetic with a size your hardware doesn't natively support is extra work.

dan04