Implement bigendian numbers in C #

Source: Internet
Author: User

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 #

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.