C# padding string with n bytes and writing it out

≯℡__Kan透↙ 提交于 2019-12-23 02:17:14

问题


I'm writing out data using BinaryWriter.
Now I'm writing out a string that will be padded to 256 bytes, with null bytes to make up for the leftover space (eg: string "hello world" takes up 11 bytes, so I will need to write another 245 null bytes).

The current approach is to just write out the string normally, calculate the length of the string and subtract that from 256 to get the desired number of null bytes, and then use a for loop to write out all of those nulls.

But maybe it's better to first build my null-padded string and then write it out all at once. How can I pad my string with null bytes to a length of n?

I guess they would be null chars rather than null bytes.


回答1:


Try using the PadRight function:

string result = "Hello World".PadRight(256, '\0');
// TODO: write the resulting string using the binary writer


来源:https://stackoverflow.com/questions/10972319/c-sharp-padding-string-with-n-bytes-and-writing-it-out

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