简体   繁体   English

如何在 C# 中将少于 8 个字节转换为 ulong?

[英]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.我需要将数据转换为字节,然后将其拆分为 64 位。 I do it by using BitConverter.我通过使用 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.但有时我的消息末尾没有 8 个字节,我想知道如何将少于 8 个字节转换为 ulong。

Is there any way to do it using BitConverter?有没有办法使用 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.0填充字节数组,直到它适合所需的大小。

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:参考:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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