Reputation: 2443
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
(3F
the wrong representation) until 255
.
It then repeats this error until 512
.
What could the bug be?
Upvotes: 1
Views: 2688
Reputation: 391316
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();
Upvotes: 4