0

I need to translate an integer into 2 bytes (0 x...) How can I do this? Click to open

int port = 7777;
byte[] bufferPost = { 0xBC, 0x5F, ..., 0xbyte1OfIntValue, 0xbyte2OfIntValue }; 
Rand Random
  • 7,300
  • 10
  • 40
  • 88

1 Answers1

2

Something like this:

  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"))));

Outcome:

  0x12 0x23 0x45 0x61 0x1e
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • 1
    Your mask and shift in the comments was far better, IMO; in addition to this being very inefficient, it is also dependent on the CPU running the code (esp: endianness) – Marc Gravell Nov 16 '18 at 12:56
  • @Marc Gravell: I see! Thank you for the comment! Let's exclude *Linq* and do it efficiently – Dmitry Bychenko Nov 16 '18 at 13:02