Pascal strings in C#

孤人 提交于 2019-12-11 06:32:25

问题


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.


回答1:


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);



回答2:


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?



来源:https://stackoverflow.com/questions/10925815/pascal-strings-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!