简体   繁体   English

C# 帮助将两个字节字拆分成字节

[英]C# help split two byte word into bytes

Hello I am relatively new to C# programming and would appreciate some help, I am writing a program that communicates with a machine via RS232 and need to send a series of bytes to initiate coms.您好,我对 C# 编程比较陌生,希望得到一些帮助,我正在编写一个通过 RS232 与机器通信的程序,需要发送一系列字节来启动 coms。 I have a two byte 16bit CRC word at the end of the packet that I think I need to split up into two bytes to fit into an array of bytes我在数据包的末尾有一个两字节的 16 位 CRC 字,我认为我需要将其分成两个字节以适应字节数组

// { <DLE> , <STX> , "G" , <DLE> , <ETX> , 16 BIT CRC CCITT split into two bytes}

byte[] byteToSend = new byte[] { 0x10, 0x02, 0x47, 0x10, 0x03, 0x421F };

When I convert 0x421F into binary and split it in half I get 0x42 and 0x1F however the problem with the less significant byte 0x1F is when it is sent it is not padded with enough zeroes.当我将 0x421F 转换为二进制并将其分成两半时,我得到 0x42 和 0x1F 但是不太重要的字节 0x1F 的问题是当它被发送时它没有填充足够的零。 I think it is just sent as <11111> instead of <00011111> as is required.我认为它只是按要求作为 <11111> 而不是 <00011111> 发送。

Any help would be MUCH appreciated THanks:)任何帮助将不胜感激谢谢:)

byte[] byteToSend = new byte[] { 0x10, 0x02, 0x47, 0x10, 0x03, 0x1F, 0x42 }
                                                               -----^

Or use BitConverter (which understands endianness):或者使用 BitConverter(它理解字节顺序):

var bytes = BitConverter.GetBytes(0x421F);
byte[] byteToSend = new byte[] { 0x10, 0x02, 0x47, 0x10, 0x03, 0x1F, 0x42 }
                                                               -----^

You need the bytes flipped if the target machine wants little-endian (likely if it's eg x86).如果目标机器需要 little-endian(可能是 x86),则需要翻转字节。 If it's big-endian, use如果是大端,请使用

byte[] byteToSend = new byte[] { 0x10, 0x02, 0x47, 0x10, 0x03, 0x42, 0x1F }
                                                               -----^

as Robert Harvey wrote.正如罗伯特哈维所写。

(If you're not sure of the endianness, just try both.) (如果您不确定字节顺序,请尝试两者。)

Is this right?这是正确的吗?

        ushort value = 0x421F;
        byte value1 = (byte)(0x421F & 0xFF);
        byte value2 = (byte)(0x421F >> 8);

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

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