As you already mentioned you will use the uint[]
for encryption.
Because of some reasons, you copy arrays with BlockCopy
. But you want to access byte[]
like an uint[]
, without converting or casting the entire array.
Then, what's something not enough? Is there something in C# can do this?
After think for one more hour, I guess what you want it for, should be the indexer
.
Here's the code. It's simple.
public partial class UIntIndexer {
static int ComputeElementCount(int size, int bytesCount) {
var r=~0;
return Math.DivRem(bytesCount, size, out r)+(r>0?1:0);
}
static int ComputeIndex(int index) {
return sizeof(uint)*index;
}
public UIntIndexer(byte[] array) {
m_Length=ComputeElementCount(sizeof(uint), (m_Array=array).Length);
}
public uint this[int index] {
set {
var startIndex=ComputeIndex(index);
var bytes=BitConverter.GetBytes(value);
var count=m_Length>1+index?sizeof(uint):m_Array.Length-startIndex;
Buffer.BlockCopy(bytes, 0, m_Array, startIndex, count);
}
get {
var startIndex=ComputeIndex(index);
if(m_Length>1+index)
return BitConverter.ToUInt32(m_Array, startIndex);
else {
var bytes=new byte[sizeof(uint)];
Buffer.BlockCopy(m_Array, startIndex, bytes, 0, m_Array.Length-startIndex);
return BitConverter.ToUInt32(bytes, 0);
}
}
}
public int Length {
get {
return m_Length;
}
}
byte[] m_Array;
int m_Length;
}
If thread safety should be concerned, you might need to keep the the source array synchronized. Following is the code for test it:
var alldata=new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
var block32=new byte[alldata.Length];
var uintIndexer=new UIntIndexer(block32);
Buffer.BlockCopy(alldata, 0, block32, 0, alldata.Length);
Debug.Print("uintIndexer.Length={0}", uintIndexer.Length);
for(var i=uintIndexer.Length; i-->0; )
Debug.Print("uintIndexer[{0}]={1}", i, uintIndexer[i]);