【问题标题】:How do I add an integer of two bytes to an array? [duplicate]如何将两个字节的整数添加到数组中? [复制]
【发布时间】:2018-11-16 12:48:00
【问题描述】:

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

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

【问题讨论】:

  • 如果你能添加一个minimal reproducible example(文字,不是图片)来说明你目前的进展,那就太棒了。
  • 尝试屏蔽Byte1 = (byte)(source & 0xFF);Byte2 = (byte)((source > 8)& 0xFF);
  • port 是否固定为 7777?您在寻找“程序员的计算器”吗? 7777 十进制是 1E61 十六进制,所以... 0x1E, 0x61 - 假设大端符号
  • @DmitryBychenko 值得一提的是,字节序在这里可能非常重要;在这种情况下,这意味着:字节 1 和字节 2 可能需要交换
  • @SeM 应该说是>> 8

标签: c# arrays byte


【解决方案1】:

类似这样的:

  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

【讨论】:

  • 您在 cmets 中的面具和换档要好得多,IMO;除了效率很低之外,它还依赖于运行代码的 CPU(尤其是字节序)
  • @Marc Gravell:我明白了!感谢您的评论!让我们排除 Linq 并高效地完成它
猜你喜欢
  • 1970-01-01
  • 2011-06-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-09
  • 1970-01-01
  • 2012-04-10
相关资源
最近更新 更多