获得在C#中的整数上下字节,并把它作为一个字符数组发送到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?
问题描述
在C我会做到这一点。
INT数= 3510;
字符上限=数>> 8;
低炭=数字功放&;&安培; 8;
SendByte(上);
SendByte(下);
块引用>
在哪里上下两个都会= 54
在C#我这样做:
INT数= Convert.ToInt16(3510);
字节上部=字节(数>→8);
低字节=字节(数字和8);
焦炭upperc = Convert.ToChar(上);
焦炭lowerc = Convert.ToChar(下)
数据=GETDM+ upperc + lowerc;
comport.Write(数据);
块引用>
然而在调试器数= 3510,上= 13,下= 0
这是没有意义的,如果我改变代码>> 6上= 54绝对是陌生的。
基本上,我只是想获得的上,从16位数字低字节,并送出GETDM后的COM端口
我怎样才能做到这一点?它是在C那么简单,但在C#我彻底难倒
解决方案您屏蔽是不正确 - 你应该对被屏蔽255(0xFF的),而不是8而言转移工作,而按位和/或对工作的价值来掩盖对...所以,如果你想只保留低8位,你需要一个面具位可通过转向其中仅低8位设置 - 即255
请注意,如果你想一个数字拆分为两个字节,它应该是一个短期或USHORT下手,而不是
INT
(具有的四的字节)。USHORT数= Convert.ToUInt16(3510);
字节上部=(字节)(数>→8);
低字节=(字节)(数量和放大器; 0xFF的);
请注意,我已经使用
USHORT
点击这里而不是字节
为按位算术更容易想想当你不需要担心符号扩展。它不会在这种情况下,实际上很重要,由于缩小转换为字节
的工作方式,但它是那种你应该考虑的事情。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 ofbyte
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 tobyte
works, but it's the kind of thing you should be thinking about.这篇关于获得在C#中的整数上下字节,并把它作为一个字符数组发送到COM端口,怎么样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!