3

I'm looking for a simple pair of functions that will convert a pair of 8-bit integers into a single 16-bit integer type and vice versa. Does anyone know of one for .NET?

[someone with more rep: please add the "c#" tag?]

flag

2 Answers

3

Here's at least one that ought do do nicely:

/// <summary>
/// converts a short into two component bytes.
/// </summary>
/// <param name="input">the short to break down.</param>
/// <param name="high">the high byte output of the function.</param>
/// <param name="low">the low byte output of the function.</param>
public static void FromShort(short input, out byte high, out byte low)
{
    high = (byte)(input >> 8);
    low = (byte)(input - ((input >> 8) << 8));
}

/// <summary>
/// converts 2 component bytes into a short.
/// </summary>
/// <param name="high">the high byte of a short.</param>
/// <param name="low">the low byte of a short.</param>
/// <returns>the short that the two bytes represented.</returns>
public static short ToShort(byte high, byte low)
{
    return (short)((short)low + ((short)high << 8));
}
link|flag
1

Not sure if this will help your solution - it's been ages since I did c#, but I remember

Convert.ToInt16
and
Int16.Parse

More Information:
http://msdn.microsoft.com/en-us/library/system.convert.toint16.aspx
http://msdn.microsoft.com/en-us/library/57w84y5d.aspx

link|flag

Your Answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.