Pregunta

Tengo un problema Tring para escribir en un archivo 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();

El problema es que se escribe en el archivo de forma incorrecta. La mayoría de las veces se escribe la información correctamente, pero una vez que se supera 127 escribe 63 (3Fthe representación equivocada) hasta 255.

A continuación, se repite este error hasta 512.

¿Cuál podría ser el error?

¿Fue útil?

Solución

Esto se debe a que estés lo codifica con ASCII, que es de 7 bits, se cortó el octavo bit y ponerlo a 0.

¿Por qué haces así? Estoy tratando de conseguir mi cabeza alrededor de lo que está haciendo allí.

¿Por qué no simplemente escribiendo la matriz de bytes se obtiene en lugar de que lo codifica?

En otras palabras, ¿por qué no utilizar este código?

//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();
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top