简体   繁体   English

在C#中将Uint64转换为5个字节,反之亦然

[英]Converting Uint64 to 5 bytes and vice versa in c#

I have an application that expects 5 bytes that is derived of a number. 我有一个应用程序,期望从一个数字派生5个字节。 Right now I am using Uint32 which is 4 bytes. 现在,我正在使用4字节的Uint32。 I been told to make a class that uses a byte and a Uint32. 我被告知要制作一个使用字节和Uint32的类。 However, im not sure how to combine them since they are numbers. 但是,由于它们是数字,因此我不确定如何组合它们。

I figured the best way may be to use a Uint64 and convert it down to 5 bytes. 我认为最好的方法可能是使用Uint64并将其转换为5个字节。 However, I am not sure how that can be done. 但是,我不确定该怎么做。 I need to be able to convert it to 5 bytes and a separate function in the class to convert it back to a Uint64. 我需要能够将其转换为5个字节,并在类中使用一个单独的函数将其转换回Uint64。

Does anyone have any ideas on the best way to do this? 有没有人对最好的方法有任何想法?

Thank you 谢谢

Use BitConverter.GetBytes and then just remove the three bytes you don't need. 使用BitConverter.GetBytes ,然后删除不需要的三个字节。

To convert it back use BitConverter.ToUInt64 remembering that you'll have to first pad your byte array with three extra (zero) bytes. 要将其转换回原位,请使用BitConverter.ToUInt64,记住您必须先用三个额外的(零)字节填充字节数组。

Just watch out for endianness. 只要注意字节顺序。 You may need to reverse your array if the application you are sending these bytes to expects the opposite endianess. 如果发送这些字节的应用程序期望相反的字节序,则可能需要反转数组。 Also the endianess will dictate whether you need to add/remove bytes from the start or end of the array. 同样,字节序将决定您是否需要从数组的开头或结尾添加/删除字节。 (check BitConverter.IsLittleEndian ) (检查BitConverter.IsLittleEndian

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

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