Skip to content

Instantly share code, notes, and snippets.

@lzybkr
Created March 15, 2017 22:11
Show Gist options
  • Save lzybkr/9940b63c8301c31316bdb3ec6305536f to your computer and use it in GitHub Desktop.
Save lzybkr/9940b63c8301c31316bdb3ec6305536f to your computer and use it in GitHub Desktop.
Formatting hex objects
using System;
using System.Runtime.InteropServices;
using System.Reflection;
namespace App
{
enum E1 : byte
{
e1 = 5
}
enum E1s : sbyte
{
e1 = -5
}
enum E2 : ushort
{
e2 = 5
}
enum E2s : short
{
e2 = -5
}
class Program
{
static byte[] Hex(object inputObject)
{
byte[] result = null;
int elements = 1;
bool isArray = false;
bool isBool = false;
bool isEnum = false;
var baseType = inputObject.GetType();
if (baseType.IsArray)
{
baseType = baseType.GetElementType();
dynamic o = inputObject;
elements = (int)o.Length;
isArray = true;
}
if (baseType.GetTypeInfo().IsEnum)
{
baseType = baseType.GetTypeInfo().GetEnumUnderlyingType();
isEnum = true;
}
if (baseType.GetTypeInfo().IsPrimitive && elements > 0)
{
if (baseType == typeof(bool))
isBool = true;
var elementSize = Marshal.SizeOf(baseType);
result = new byte[elementSize * elements];
if (!isArray)
{
inputObject = new object[1] { inputObject };
}
int index = 0;
foreach (dynamic o in (Array)inputObject)
{
if (elementSize == 1)
{
result[index] = (byte) o;
}
else
{
// bool is 4 bytes apparently
dynamic toBytes;
if (isEnum)
{
toBytes = Convert.ChangeType(o, baseType);
}
else if (isBool)
{
toBytes = Convert.ToInt32(o);
}
else
{
toBytes = o;
}
var bytes = BitConverter.GetBytes(toBytes);
for (int i = 0; i < bytes.Length; i++)
{
result[i + index] = bytes[i];
}
}
index += elementSize;
}
}
return result ?? new byte[0];
}
static void Print(byte[] bytes)
{
Console.Write("{0}:", bytes.Length);
foreach (var b in bytes)
{
Console.Write(" {0:x}", b);
}
Console.WriteLine();
}
static void Main(string[] args)
{
Print(Hex((UInt64) 42));
Print(Hex((Int64) 42));
Print(Hex((UInt32) 42));
Print(Hex((Int32) 42));
Print(Hex((UInt16) 42));
Print(Hex((Int16) 42));
Print(Hex((byte) 42));
Print(Hex((sbyte) 42));
Print(Hex(1.0f));
Print(Hex(1.0d));
Print(Hex(true));
Print(Hex(E1.e1));
Print(Hex(E1s.e1));
Print(Hex(E2.e2));
Print(Hex(E2s.e2));
Print(Hex(new long[] {1, 2, 3}));
Print(Hex(new int[] {1, 2, 3}));
Print(Hex(new short[] {1, 2, 3}));
Print(Hex(new byte[] {1, 2, 3}));
Print(Hex(new E2s[] {E2s.e2, E2s.e2}));
Print(Hex(new E2[] {E2.e2, E2.e2}));
Print(Hex(new E1s[] {E1s.e1, E1s.e1}));
Print(Hex(new E1[] {E1.e1, E1.e1}));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment