简体   繁体   中英

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.

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM