C #, la scrittura dei dati binari
-
11-09-2019 - |
Domanda
Ho un problema Tring per scrivere in un file binario.
//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();
Il problema è che si scrive nel file in modo non corretto. La maggior parte del tempo che scrive le informazioni in modo corretto, ma una volta che supera 127
scrive 63
(3F
the rappresentazione sbagliata) fino 255
.
E poi ripete questo errore finché 512
.
Quale potrebbe essere il bug?
Soluzione
Questo perché si sta codificando con ASCII, che è a 7 bit, sarà tagliato fuori l'8 bit e impostato a 0.
Perché stai facendo in questo modo? Sto cercando di ottenere la mia testa intorno a quello che stai facendo lì.
Perché non semplicemente scrivendo l'array di byte che si ottiene, invece di codifica esso?
In altre parole, perché non si utilizza questo codice?
//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();
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow