![]() |
Languages »
C# »
Samples
License: The Code Project Open License (CPOL)
An Addressed Byte ArrayBy BinariusA class to control individual bits in a byte array |
C# (C# 2.0, C# 3.0), .NET (.NET 2.0, .NET 3.0), Dev
|
|
Advanced Search Add to IE Search |
|
|
|
||||||||||||||||
A few days ago, I needed to keep track of operator state (on/off) for a large number of operators. For this, I intended to use a BitArray, however when the number of operators was set to Int32.MaxValue, I got an OutOfMemoryException much before the count was finalized. I posted a question here where you can read the complete thread. In the end, I decided to write a class to work around.
I used a Byte[] and created a method to read and write different bits in any byte.
Let's say that all I need to work with are 16 bits, the class creates a byte[] of 2 elements with each holding value 0xff (all bits are true).
byte[] b = new byte[2]; //b[0] and b[1]
Now let's say that I want to set bit 10 to false. Bit 10 is (obviously) in b[1]. I create a mask 0x04 to 'extract' the relevant bit and work on it.
In the attached project, I used the class to work out Prime Numbers using the Sieve of Eratosthenes method. Incidentally while creating this example, I also tried using BitArray for working on a large set of integers (1 to Int32.MaxValue) and I got the same OutOfMemoryException which I did not when I used the AddressingByte class.
When a instance of the PrimeNumberCalculator class is created, it creates an instance of AddressingByte, passing to it the number of bytes required and the initial value (0xff since I need all bits to be true at startup). To work the sieve, calls to two methods (GetValueAt(Int32 AddressOfBit) and SetValueAt(Int32 AddressOfBit, Boolean BoolValue)) are made...
//Calculation to Find Primes
for (Int32 i = 2; i < _topNumber; i++)
if (_numbers.GetValueAt(i))
for (Int32 j = i * 2; j < _topNumber; j += i)
_numbers.SetValueAt(j, false);
... where _topNumber is the maximum number I want to work to and _numbers is the instance of AddressByte.
A bit of a disclaimer. The solution supplied to the problem described here works. It is not fast but I was not after speed and/or efficiency.
General
News
Question
Answer
Joke
Rant
Admin
|
PermaLink |
Privacy |
Terms of Use
Last Updated: 28 Apr 2008 Editor: Deeksha Shenoy |
Copyright 2008 by Binarius Everything else Copyright © CodeProject, 1999-2009 Web21 | Advertise on the Code Project |