Reputation: 481
Im having trouble with some conversions, and can´t find whats wrong with the code, or with the idea of what it has to do.
I have the following byte[]
byte[] bytes = {0xFF, 0xFF, 0xFE};
which I convert into ulong this way:
ulong next = ((uint)((((0x00 << 4) | bytes[0]) << 16) | ((bytes[1] << 8) | bytes[2])));
next thing I add 1 to next:
next++;
Then, I want to convert the ulong, back to the byte array. I tryed with several bcd algorithms found here and on the web, but I cannot get the result I am expecting:
byte[] bytes = {0xFF, 0xFF, 0xFF};
insted of
{ 0x15, 0x72, 0x77, 0x16}
which I am getting with most of the solutions I have tryed.
Here is one of the algorithms I have used:
static Byte[] CopyAsBCD(UInt32 value)
{
Byte[] buffer = new byte[4];
Int32 offset = 0;
var length = 4;
var s = value.ToString();
var stringIndex = s.Length - 1;
var bufferIndex = offset + length - 1;
var isLower = true;
try
{
while (bufferIndex >= offset && stringIndex > -1)
{
if (isLower)
buffer[bufferIndex] = Byte.Parse(s[stringIndex].ToString());
else
buffer[bufferIndex] += (Byte)(Byte.Parse(s[stringIndex].ToString()) << 4);
if (!isLower)
bufferIndex--;
isLower = !isLower;
stringIndex--;
}
}
catch
{
}
return buffer;
}
What I am doing wrong? or I have a concept problem?
Upvotes: 0
Views: 2701
Reputation: 19646
Can you not just use:
//Array padded to 8 bytes, to represent a ulong
byte[] bytes = {0, 0, 0, 0, 0, 0xFF, 0xFF, 0xFE};
var longBytes = BitConverter.ToUInt64(bytes, 0);
var arrayBytes = BitConverter.GetBytes(longBytes);
Note: you may need to reverse the array, depending on the Endianness of the system you're on (in which case you may need to add padding to the other side).
Upvotes: 2