简体   繁体   中英

Pascal strings in C#

I'm working on an audio library in C# and am working on the WAVE file format ATM. According to the very informative website that I am using, WAVE using Pascal style strings. I have been Googling for over 20 minutes and have come up only with a C to Pascal converter .

I know how Pascal and C strings compare (C code):

char *cStr = "Test"; // C - produces {'T', 'e', 's', 't', '\0'}
char pascal[] = {4, 'T', 'e', 's', 't'}; // Pascal

If it helps, I am using System.IO.BinaryReader to parse the file.

Well if you are using BinaryReader this should be pretty easy.

var size = rd.ReadByte();
var body = rd.ReadBytes(size);
var text = System.Text.Encoding.ASCII.GetString(body);

The basic idea behind a Pascal string is that the first byte holds the string length, and subsequent bytes hold the string data (limiting strings to 255 characters).

I would work with a byte array and use the string to byte conversion methods in C# to populate it. See the accepted answer of the question below to understand how to convert a C# string to a byte array, and remember to offset everything 1 array position to allow room for the 0th byte, holding the string length, and remember to populate the 0th byte with the actual string length. Check your input string length to make sure it's not over 255 characters :-)

How do I get a consistent byte representation of strings in C# without manually specifying an encoding?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM