StringBuilder append byte without formatting

user1922299 picture user1922299 · Dec 21, 2012 · Viewed 9.5k times · Source
DateTime todayDateTime = DateTime.Now;
StringBuilder todayDateTimeSB = new StringBuilder("0");
todayDateTimeSB.Append(todayDateTime.ToString("MMddyyyy"));
long todayDateTimeLongValue = Convert.ToInt64(todayDateTimeSB.ToString());
// convert to byte array packed decimal
byte[] packedDecValue = ToComp3UsingStrings(todayDateTimeLongValue); 
// append each byte to the string builder
foreach (byte b in packedDecValue)
{
    sb.Append(b); // bytes 56-60
}
sb.Append(' ', 37);

The above code takes the current date time, formats it into a long value and passes that to a method which converts it to a packed decimal format. I know that the above works since when I step though the code the byte array has the correct Hex values for all of the bytes that I am expecting.

However the above is the code I am having issues with, specifically I have researched and found that the string builder .Append(byte) actually does a ToString() for that byte. Which is altering the value of the byte when it adds it to the string. The question is how do I tell the StringBuilder to take the 'byte' as is and store it in memory without formatting/altering the value. I know that there is also a .AppendFormat() which has several overloads which use the IFormatProvider to give lots and lots of options on how to format things but I don't see any way to tell it to NOT format/change/alter the value of the data.

Answer

Mark Byers picture Mark Byers · Dec 21, 2012

You can cast the byte to a char:

sb.Append((char)b);

You can also use an ASCIIEncoding to convert all the bytes at once:

string s = Encoding.ASCII.GetString(packedDecValue);
sb.Append(s);