I am working on writing my own DNS server in .net core. I'm at the stage where I am encoding the response payload to send back, and the schema shows that most of the numbers are encoded as 16 bit numbers. C#'s ints are 32 bit numbers. Not a big deal, I'm just dropping off the remaining 16 bits from the front of the number I have no problem with that.
I was doing this by hand until I discovered the System.BitConverter class. I tried using it, however, and the results I came up with were reversed of what it came up with.
For example:
using System;
var myInt = 15;
byte[] data = new byte[2];
data[0] = (byte)(myInt >> 8);
data[1] = (byte)(myInt & 255);
var myIntStr = "";
foreach(var b in data)
{
myIntStr += System.Convert.ToHexString(new byte[]{ b });
myIntStr += " ";
}
Console.WriteLine(myIntStr);
var myShort = System.Convert.ToInt16(myInt);
byte[] data2 = System.BitConverter.GetBytes(myShort);
myIntStr = "";
foreach(var b in data2)
{
myIntStr += System.Convert.ToHexString(new byte[]{ b });
myIntStr += " ";
}
Console.WriteLine(myIntStr);
This code produces the following result:
00 0F
0F 00
It's my understanding that 000F is 15 where as 0F00 is 3840. Am I not understanding bit shifting correctly? I literally just started working with actual bits last night lol.
Thanks for reading this and thanks in advance for your help!