Created
July 21, 2011 17:30
-
-
Save joefearnley/1097708 to your computer and use it in GitHub Desktop.
Convert string to packed ascii byte array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <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