A dll for USB communications reads data and puts it into a StringBuilder instance, bRx. How can the bytes of data in bRx be moved to a byte buffer to ultimately be written to a file?
Asked
Active
Viewed 2,019 times
-1
-
2if you're written them to a file, why do you need them as byte buffer ? you can just use `File.WriteAllText` – Noctis Oct 26 '14 at 05:13
-
Which bytes? Why are they in a StringBuilder in the first place? Do you want a byte representation of _text_ in the StringBuilder? Or does the text in the StringBuilder represent binary data in some numeric format (e.g. hexadecimal)? You really need to post a less-vague question. Give some example code of what you're dealing with, along with some sample data. – Peter Duniho Oct 26 '14 at 06:23
2 Answers
2
It may vary depending on how the string is encoded / what is stored in it
But try this:
byte[] b = System.Text.Encoding.UTF8.GetBytes(sb.ToString());
or
byte[] b = System.Text.Encoding.ASCII.GetBytes(sb.ToString());
See the SO thread regarding String which should apply to StringBuilder:
-
I've tried your 1st suggestion. The first byte in SB is 0xff. The problem is that it gets translated to two bytes in the byte buffer, 0xC3 followed by 0xBF. – DMaxJones Oct 26 '14 at 05:21
0
I think there is a separator needed if you are adding using Append(byte value)
. Microsoft has an example there with a " "
- http://msdn.microsoft.com/en-us/library/86yy043k(v=vs.110).aspx
I've prepared an example that fits more to your needs I think:
const char separator = ';';
byte[] inputBytes = { 255, 16, 1 };
StringBuilder sb = new StringBuilder();
foreach (byte b in inputBytes)
sb.Append(b).Append(separator);
// remove a separator in a tail
sb.Remove(sb.Length - 1, 1);
var byteArrayActual = sb.ToString()
.Split(separator)
.Select(x => byte.Parse(x))
.ToArray();
Debug.Assert(Enumerable.SequenceEqual(inputBytes, byteArrayActual));
After the above code executed there is the same array (as initial) that is ready to be saved to a file: Byte[] (3 items) 255 16 1
.

TarasB
- 2,407
- 1
- 24
- 32