In our PC, the number of C # Is littleendian, causing a lot of inconvenience in network protocols and File Parsing. Therefore, I wrote a bigendian digital class, record it here and it will be frequently used in the future.
Static class bigendianuinthelper
{
Public static uint touint32 (byte [] data)
{
Contract. Assume (data. Length <= 4 );
Return bitconverter. touint32 (New byte [4-Data. Length]. Concat (data). Reverse (). toarray (), 0 );
}
Public static byte [] tobytes (uint num, int size)
{
Contract. Assume (size <= 4 );
Return bitconverter. getbytes (Num). Take (size). Reverse (). toarray ();
}
}
[Structlayout (layoutkind. Sequential)]
Struct bigendianuint24
{
Const int size = 3;
[Financialas (unmanagedtype. byvalarray, sizeconst = size)]
Byte [] data;
Public Static Implicit operator uint (bigendianuint24 d) {return bigendianuinthelper. touint32 (D. data );}
Public Static Implicit operator bigendianuint24 (uint d) {return New bigendianuint24 () {DATA = bigendianuinthelper. tobytes (D, size )};}
Public override string tostring () {return (uint) This). tostring ();}
}
[Structlayout (layoutkind. Sequential)]
Struct bigendianuint32
{
Const int size = 4;
[Financialas (unmanagedtype. byvalarray, sizeconst = size)]
Byte [] data;
Public Static Implicit operator uint (bigendianuint32 d) {return bigendianuinthelper. touint32 (D. data );}
Public Static Implicit operator bigendianuint32 (uint d) {return New bigendianuint32 {DATA = bigendianuinthelper. tobytes (D, size )};}
Public override string tostring () {return (uint) This). tostring ();}
}
In fact, here the two functions of bigendianuinthelper should be optimized. Here, bitconverter's ready-made method is directly used for the sake of simplicity. You need to fix it later.
Related Articles: perform operations similar to bit domains in C #