tags:

views:

361

answers:

1

I have a problem tring to write to a binary file.

//This is preparing the counter as binary
int nCounterIn = ...;
int nCounterTotalInNetwork = System.Net.IPAddress.HostToNetworkOrder(nCounterIn);
byte[] byteFormat = BitConverter.GetBytes(nCounterTotalInNetwork);
char[] charFormat = System.Text.ASCIIEncoding.ASCII.GetChars(byteFormat);
string strArrResults = new string(charFormat);

//This is how writing it to a file using a BinaryWriter object

m_brWriter.Write(strArrResults.ToCharArray());
m_brWriter.Flush();

The problem is that it writes to the file incorrectly. Most of the time it writes information correctly, but once it surpasses 127 it writes 63 (3Fthe wrong representation) until 255.

It then repeats this error until 512.

What could the bug be?

+3  A: 

That is because you're encoding it with ASCII, which is 7-bit, it will cut off the 8th bit and set it to 0.

Why are you doing it this way? I'm trying to get my head around what you're doing there.

Why are you not simply writing the byte array you get instead of encoding it?

In other words, why don't you use this code?

//This is preparing the counter as binary
int nCounterIn = ...;
int nCounterTotalInNetwork = System.Net.IPAddress.HostToNetworkOrder(nCounterIn);
byte[] byteFormat = BitConverter.GetBytes(nCounterTotalInNetwork);
m_brWriter.Write(byteFormat);
m_brWriter.Flush();
Lasse V. Karlsen
Why even a writer - just `Write` to the `Stream` ;-p
Marc Gravell
Why write to a stream?File.Appendtext("filepath", your counter);
Vitaliy
Sure, but if he's going to write other parts using that writer, I felt it safest to just keep it, but yeah, if he's not going to use other parts of it, I'd go for a simple stream.
Lasse V. Karlsen
Yes I a uing also a data messsage in continous to that counter. How can I use only a stream I need the data to be binary. I thoght that binarywrite converts the data to binary.
Roman Dorevich
The problem is that I need to add this counter to a message and print it in one flush, when I am trying to print it it is printed as 8 bytes instead of 4 and wrong value.I added before the printing ://This is preparing the counter as binaryint nCounterIn = ...;int nCounterTotalInNetwork = System.Net.IPAddress.HostToNetworkOrder(nCounterIn);byte[] byteFormat = BitConverter.GetBytes(nCounterTotalInNetwork);string strV = BitConvertor.ToString(byteFormat);strV += //Message string DATA. m_brWriter.Write(strV);m_brWriter.Flush();
Roman Dorevich