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.
To be a little more creative
Shouldn't it be:
You probably want to and it with
0x00FF
Full example:
Even if the accepted answer fits the question, I consider it incomplete due to the simple fact that the question contains int and not short in header and it is misleading in search results, and as we know Int32 in C# has 32 bits and thus 4 bytes. I will post here an example that will be useful in the case of Int32 use. In the case of an Int32 we have:
And as such, I have created the following method for converting the Int32 value into a little endian Hex string, in which every byte is separated from the others by a Whitespace. This is useful when you transmit data and want the receiver to do the processing faster, he can just Split(" ") and get the bytes represented as standalone hex strings.
Usage:
The result is:
If it is hard to understand the method which I created, then the following might be a more comprehensible one:
Remarks:
Hope this will help someone!
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).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.