Skip to content

Instantly share code, notes, and snippets.

@joefearnley
Created July 21, 2011 17:30
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joefearnley/1097708 to your computer and use it in GitHub Desktop.
Save joefearnley/1097708 to your computer and use it in GitHub Desktop.
Convert string to packed ascii byte array
/// <summary>
/// Convert a string to packed ascii byte array
/// </summary>
/// <param name="toBePacked">ascii string to be packed</param>
/// <returns>packed ascii byte array</returns>
public static byte[] PackAscii(string toBePacked)
{
// convert the ascii to a byte array
byte[] ascii = System.Text.Encoding.ASCII.GetBytes(toBePacked.PadRight(8, ' '));
List<byte> packedAscii = new List<byte>();
int index = 0;
// loop through four bytes at a time and pack them into three bytes.
for (int i = 0; i < ascii.Length; i = i + 4)
{
// perform the bitwise operations to truncate the 6th and 7th bit
uint result = (uint)(((ascii[index] & 0x3F) << 18) +
((ascii[index + 1] & 0x3F) << 12) +
((ascii[index + 2] & 0x3F) << 6) +
(ascii[index + 3] & 0x3F));
// Convert the uint array to byte. If the bitconverter class
// is little endian, needs to be reversed.
byte[] packedTemp = BitConverter.GetBytes(result);
if (BitConverter.IsLittleEndian)
{
// Reverse the array and skip the first byte
Array.Reverse(packedTemp);
for (int k = 1; k < 4; k++)
{
packedAscii.Add(packedTemp[k]);
}
}
else
{
// Not little endian so just add the first three bytes.
for (int j = 0; j < 3; j++)
{
packedAscii.Add(packedTemp[j]);
}
}
index += 4;
}
return packedAscii.ToArray();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment