How do I convert less than 8 bytes to a ulong in C#?

So I am implementing a cryptography algorithm now. And I need to convert data to bytes and then split it in 64 bits. I do it by using BitConverter.
But sometimes I don't have 8 bytes in the end of a message and I wonder how to convert less than 8 bytes to ulong.

Is there any way to do it using BitConverter? I tried shifting the bytes but it's too complicated since I don't know the exact amount of bytes.

Upvotes: 2

Views: 944

Answers (1)

Gabe
Gabe

Reputation: 971

Fill the byte array with 0s until it fits the size required.

byte[] bytes = new byte[255]{ 0x1F, 0x1A, 0x1B, 0x2C, 0x3C, 0x6D, 0x1E }; //7 bytes

while(bytes.Length < 8){
   bytes.Concat(new byte[] { 0x00 });
}

long res = BitConverter.ToUInt64(bytes, 0);

Reference:

Upvotes: 0

Related Questions