首页 > 解决方案 > 如何将两个字节的整数添加到数组中?

问题描述

我需要将一个整数转换为 2 个字节 (0 x...) 我该怎么做? 点击打开

int port = 7777;
byte[] bufferPost = { 0xBC, 0x5F, ..., 0xbyte1OfIntValue, 0xbyte2OfIntValue }; 

标签: c#arraysbyte

解决方案


像这样的东西:

  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

推荐阅读