开发者

C# binary to string

I am converting integer number to binary and put it in a header of a data message. For instance the first meesage that arrived, I would convert the counter to binary that take 4 bytes and had the data message, which is a reguler message containning a, b, c etc'.

Here is how I convert the counter :

//This is preparing the counter as binaryint 
nCtrIn = ...;
int nCtrInNetwork = System.Net.IPAddress.HostToNetworkOrder(nCtrIn);
byte[] ArraybyteFormat = BitConverter.GetBytes(nCtrInNetwork);

Now the problem is that now in to ta开发者_Go百科ke a nother string copy the byteFormat to the beginning of a string and in addition to add the string data.

I do that because I want only in the end to write to the file using binary writer

m_brWriter.Write(ArraybyteFormat);
m_brWriter.Flush();


You can simplify by letting the BinaryWriter directly write the int - no need to conver to byte[] first.

The other problem is writing the message, it can be done like:

m_brWriter.Write(nCounterIn); 
string msg = ....; // get it as 1 big string
byte[] textData = Encoding.UTF8.GetBytes(msg);
m_brWriter.Write(textData); 

Or, even easier and also easier to read back:

m_brWriter.Write(nCounterIn); 
m_brWriter.Write(msg); 

But note that the BinaryWriter will now put it's own lentgh-prefix in front of the string.


If it's important to write to the stream in single call you can concatenate the arrays:

var intArray = new byte[4];       // In real code assign
var stringArray = new byte[12];   // actual arrays

var concatenated = new byte[16];
intArray.CopyTo(concatenated, 0);
stringArray.CopyTo(concatenated, 4);

m_brWriter.Write(concatenated);
m_brWriter.Flush();

Did you consider writing the arrays in two calls to Write?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜