在 C# 中获取整数的上下字节并将其作为 char 数组发送到 com 端口,如何? [英] Getting upper and lower byte of an integer in C# and putting it as a char array to send to a com port, how?

查看:26
本文介绍了在 C# 中获取整数的上下字节并将其作为 char 数组发送到 com 端口,如何?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C 中我会这样做

<块引用>

整数 = 3510;

字符上限=数字>>8;

char lower = 数字 &&8;

发送字节(上);

发送字节(下);

upper 和 lower 都 = 54

在 C# 中我这样做:

<块引用>

 int number = Convert.ToInt16("3510");字节上限 = 字节(数字 >> 8);字节低=字节(数字& 8);char upperc = Convert.ToChar(upper);char lowerc = Convert.ToChar(lower);数据=GETDM";+ 大写 + 小写;comport.Write(数据);

但是在调试器编号 = 3510 中,上 = 13 下 = 0这没有任何意义,如果我将代码更改为 >>6 upper = 54,这太奇怪了.

基本上我只是想从16位数字中获取高低字节,并在GETDM"之后将其发送到com端口

我该怎么做?在 C 中它是如此简单,但在 C# 中我完全被难住了.

解决方案

您的掩码不正确 - 您应该针对 255 (0xff) 而不是 8 进行掩码.移位是按照要移位的位"进行的,而按位和/或对要屏蔽的值进行操作...因此,如果您只想保留底部 8 位,则需要一个仅设置底部 8 位的掩码 - 即 255.

请注意,如果您想将一个数字拆分为两个字节,那么它实际上应该是一个 short 或 ushort,而不是一个 int(它有 四个 字节).

ushort number = Convert.ToUInt16("3510");高字节=(字节)(数字>>8);低字节 = (byte) (number & 0xff);

请注意,我在这里使用了 ushort 而不是 byte,因为当您不需要担心符号扩展时,按位算术更容易考虑.由于缩小转换为 byte 的工作方式,在这种情况下实际上并不重要,但这是您应该考虑的事情.

In C I would do this

int number = 3510;

char upper = number >> 8;

char lower = number && 8;

SendByte(upper);

SendByte(lower);

Where upper and lower would both = 54

In C# I am doing this:

            int number = Convert.ToInt16("3510");
            byte upper = byte(number >> 8);
            byte lower = byte(number & 8);
            char upperc = Convert.ToChar(upper);
            char lowerc = Convert.ToChar(lower);
            data = "GETDM" + upperc + lowerc;
            comport.Write(data);

However in the debugger number = 3510, upper = 13 and lower = 0 this makes no sense, if I change the code to >> 6 upper = 54 which is absolutely strange.

Basically I just want to get the upper and lower byte from the 16 bit number, and send it out the com port after "GETDM"

How can I do this? It is so simple in C, but in C# I am completely stumped.

解决方案

Your masking is incorrect - you should be masking against 255 (0xff) instead of 8. Shifting works in terms of "bits to shift by" whereas bitwise and/or work against the value to mask against... so if you want to only keep the bottom 8 bits, you need a mask which just has the bottom 8 bits set - i.e. 255.

Note that if you're trying to split a number into two bytes, it should really be a short or ushort to start with, not an int (which has four bytes).

ushort number = Convert.ToUInt16("3510");
byte upper = (byte) (number >> 8);
byte lower = (byte) (number & 0xff);

Note that I've used ushort here instead of byte as bitwise arithmetic is easier to think about when you don't need to worry about sign extension. It wouldn't actually matter in this case due to the way the narrowing conversion to byte works, but it's the kind of thing you should be thinking about.

这篇关于在 C# 中获取整数的上下字节并将其作为 char 数组发送到 com 端口,如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆