Skip to content

Instantly share code, notes, and snippets.

@rquackenbush
Created May 15, 2017 19:02
Show Gist options
  • Save rquackenbush/6e0dfa4b8a4cacb4b0b1444e0c553d9b to your computer and use it in GitHub Desktop.
Save rquackenbush/6e0dfa4b8a4cacb4b0b1444e0c553d9b to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
namespace StructDesigner.Runtime.Extensions
{
public static class RegisterExtensions
{
/// <summary>
/// Converts an array of registers into a byte array.
/// </summary>
/// <param name="values"></param>
/// <returns></returns>
public static byte[] ToBytes(this ushort[] values)
{
//Allocate space for the bytes.
var bytes = new List<byte>(values.Length * 2);
foreach (var value in values)
{
bytes.Add((byte)(value >> 8));
bytes.Add((byte)value);
}
return bytes.ToArray();
}
/// <summary>
/// Converts a byte array into registers. Requires that the source array is of an even length.
/// </summary>
/// <param name="values"></param>
/// <returns></returns>
public static ushort[] ToRegisters(this byte[] values)
{
if (values.Length % 2 != 0)
throw new ArgumentException($"The length of '{nameof(values)}' must be even.", nameof(values));
//Calculate how many regsiters we will have
var numberOfRegisters = values.Length / 2;
//Create a place for the registers.
var registers = new ushort[numberOfRegisters];
//Deal with each register
for (var index = 0; index < numberOfRegisters; index++)
{
var msb = (ushort)(((ushort)values[index * 2]) << 8);
var lsb = (ushort)values[(index * 2) + 1];
registers[index] = (ushort)(msb | lsb);
}
return registers;
}
/// <summary>
/// Gets a bit from a byte.
/// </summary>
/// <param name="value"></param>
/// <param name="bitPosition"></param>
/// <returns></returns>
public static bool GetBit(this byte value, int bitPosition)
{
return (value & (1 << bitPosition)) > 0;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment