Common decoding methods of C # byte array

Source: Internet
Author: User

In some cases, such as serial communication or reading binary files, unobstructed will get a byte array in the form of data.

However, for this data processing is often distressing, because in general communication situations, not a byte represents a character or some data, but the data is mixed between bytes and byte.

Read the file to get the situation:

New FileInfo (@ "E:\ABC. DAT"); long len =new FileStream (@ "E:\ABC. DAT", FileMode.Open); byte New byte  0, (int) len); fs. Close ();

1: Converts a byte to a 16-binary character representation

);   // 16 binary ()). PadLeft (2'0'"";   // converted to 2-character-length (insufficient left-side complement 0)

Conversion of 2:ASCII encoded storage (4 to 17 of byte array buffer is an ASCII character stored time)

stringStr_stime = Encoding.ASCII.GetString (buffer,4, -); DateTime stime=NewDateTime (Int32.Parse (str_stime. Substring (0,4) ), Int32.Parse (Str_stime. Substring (4,2) ), Int32.Parse (Str_stime. Substring (6,2) ), Int32.Parse (Str_stime. Substring (8,2) ), Int32.Parse (Str_stime. Substring (Ten,2) ), Int32.Parse (Str_stime. Substring ( A,2) ), Int32.Parse (Str_stime. Substring ( -,3)));

3: If a data is stored between bytes

such as 2 bytes of 0000|0000| | 0000|0000

BYTE 0 byte 1

The first 5 bits of the two bytes represent a data, and 6 bits represent a data, and the last 5 bits represent a data

Because int is 32-bit data in C #, you can store 4 bytes of data, Int16 can represent 2 bytes, and then handle it by shifting and bitwise operations.

  

Int16 iData = buffer[1] + (buffer[080x1F50x3F one by one0x1F;  

If there is any mistake, please advise.

Common decoding methods of C # byte array

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.