Skip to main content
 首页 » 编程设计

C#,写入二进制数据

2024年02月24日13think

我在尝试写入二进制文件时遇到问题。

//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(); 

问题是它写入文件不正确。大多数时候它会正确写入信息,但一旦超过 127 就会写入 63(3F 错误表示)直到 255。

然后重复此错误直到 512。

错误可能是什么?

请您参考如下方法:

那是因为你用 ASCII 编码,它是 7 位的,它会截掉第 8 位并将其设置为 0。

你为什么要这样做?我正在努力了解你在那里做什么。

为什么不简单地编写您获得的字节数组而不是对其进行编码?

换句话说,你为什么不使用这段代码?

//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();