C # How to put the serial port received two bytes, the synthesis of a short integer

Source: Internet
Author: User

c#2013101301

Here are two simple ways to demonstrate:

1. Use the shift character.

Cases:

byte[] bytes = new byte[2]{0x31,0x32};
Short U16;
U16 = (short) ((Bytes[0] << 8) + bytes[1]);
Button1. Text = U16. ToString ();
Come to the result:

hex:3132

dec:12594

2. Use cast, 2nd byte *256

byte[] bytes = new byte[2]{0x31,0x32};
Short U16;
U16 = (short) (short) bytes[0] * 256 + (short) bytes[1];//There must be a cast in the front, because the middle 256 defaults to type int
button1. Text = U16. ToString ();

hex:3132

dec:12594





Related Article

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.