我需要将整数转换为2个字节(0 x ...),该怎么做?
int port = 7777;
byte[] bufferPost = { 0xBC, 0x5F, ..., 0xbyte1OfIntValue, 0xbyte2OfIntValue };
答案 0 :(得分:2)
类似这样的东西:
byte[] bufferPost = new byte[] {
0x12, 0x23, 0x45};
int port = 7777;
Array.Resize(ref bufferPost, bufferPost.Length + 2);
bufferPost[bufferPost.Length - 2] = (byte)(port & 0xFF);
bufferPost[bufferPost.Length - 1] = (byte)((port >> 8) & 0xFF);
// Let's have a look what's going on
Console.Write(string.Join(" ", bufferPost.Select(item => "0x" + item.ToString("x2"))));
结果:
0x12 0x23 0x45 0x61 0x1e
答案 1 :(得分:0)
这不是最好的解决方案,但它可行
int port=7777;
string temp=Convert.ToString(port);
int firstbyte=Convert.ToInt32(temp.SubString(0,2));
int secondbyte=Convert.ToInt32(temp.Substring(2));
byte b1=(byte)firstbyte;
byte b2=(byte)secondbyte;