請教各位前輩,我把數字 2971 拆成 低位元 71 及 高位元 29 傳送,並傳送 'A'
作為來源的識別,我用 C# 接收寫成文字檔案後,計畫從文字檔中讀取字元取得他的16
進制數值,作高低位元組合,還原 2971 的動作,以便做後續的數學運算。但是在轉換
的部份,發生困難,懇請各位前輩指正錯誤,謝謝!!
**************************************************************************
以下為接收寫成的文字檔案 C:\receiveData.txt
A? A? A? A? A? A? A? A? A? A? A? A? A? A? A? A? AA? A? A? A? A? A? A? A? A
? A? A? A? A A? A? A? AA? A? A? A? A? A? A? A? A? A? A? A? A? A? A? A?
AA? A? A? A? A? A? A? A? A A? A? A? A? A? A? A? AA? A? A? A? A? A? A?
A? A? A? A? A? A? A? A? A? AA? A? A? A? A A? A? A? A? A? A? A? A? A
private void button3_Click(object sender, EventArgs e)
{
string str;
int position;
int result_Low;
int result_High;
string result;
StreamReader sr = new StreamReader(@"C:\receiveData.txt");
str = sr.ReadToEnd(); // 讀取整篇文字檔案
textBox1.Text = str; // 顯示文字檔案
position = str.IndexOf('A'); // Indexof:字串中搜尋字元,傳回特定字元在
字串中的索引位置
while (position != -1) // 字串中如果找不到'A',回傳 -1
{
richTextBox1.Text += position.ToString(); // 顯示'A'的位置
richTextBox1.Text += '\n'; // 顯示換行
richTextBox1.Text += str.Substring(position, 3); // Substring:取得子字串
//************* 以下開始發生轉換錯誤訊息***********************
result_Low = Convert.ToInt16(str.Substring(position + 1, 1));
result_High = Convert.ToInt16(str.Substring(position + 2, 1));
result = ((result_High << 8) | result_Low).ToString();
//*************************************************************
richTextBox1.Text += '\n'; // 顯示換行
str = str.Remove(position, 3); // Remove : 移除指定位置的指定長度字串
FileInfo fileInfo = new FileInfo(@"C:\result.txt");
// 開啟新增的文字檔案
StreamWriter sw = fileInfo.AppendText();
sw.WriteLine(result);
sw.Flush(); // 將緩衝區資料寫入檔案
sw.Close(); // 關閉檔案
position = str.IndexOf('A'); // 再做一次搜尋字元回傳值給 while 作判斷
}
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.112.27.180
Using Microsoft.VisualBasic.Devices;
Computer My = new Computer();
string Mdata;
Mdata = My.FileSystem.ReadAllText("C:\\Test.txt");
Console.Write(Mdata);
我都是這樣讀txt裡的資料的..不知道有回答到你的問題嗎??
如果有錯還請個位指教一下..感謝囉
--
別人笑我太瘋顛 我笑他人看不穿
不見五陵豪傑墓 無花無酒鋤作田
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 211.20.51.237
你的程式碼引發了 FormatException
Convert.ToInt16 功能 : ASCII 字串數字轉換成 Binary
所以, 以字串參數來說 ...
1.它的內容 : "0" ~ "9" 和 "+/-" 符號組成的數字字串, 不然會引發 FormatException
2.它的範圍 : 就只能在 "-32768" ~ "32768", 不然會引發 OverflowException
這樣, 你知道你的問題出在哪邊了嗎?
所以, 請用 BinaryReader ...
--
[1;31m私生存道 [m
[1;32m今未來唯一 [m
[1;33m私自身闇黑 [m
[1;37m即「 [36m [37m」 [m
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 220.133.168.73