讀取UDP數(shù)據(jù)包,需要將單個字節(jié)轉(zhuǎn)換為序數(shù)值(int)?;蛘咭粋€ 4 字節(jié)整數(shù)值到 int。但我感興趣的值是 0、1 或 2(有意義的單字節(jié)),因此實際上不需要讀取所有 4 個字節(jié)。private async void Button1_ClickAsync(object sender, EventArgs e){ try { using (var TheudpClient = new UdpClient(2237)) { TheudpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); var receivedResults = await TheudpClient.ReceiveAsync(); MsgText = Encoding.ASCII.GetString(receivedResults.Buffer); MsgTypeStr = MsgText.Substring(11,1); MsgTypeInt = (int)MsgTypeStr; // this line blows up... // MsgTypeInt = int.Parse(MsgTypeStr, System.Globalization.NumberStyles.HexNumber); // this blows up // MsgTypeInt = Int32.Parse(MsgTypeStr); // this blows up richTextBox1.Text = "\nLength: " + MsgText.Length + " Type " + MsgTypeInt.ToString(); richTextBox1.Text = "\nReceived data: " + MsgText; } } catch(Exception ex) { richTextBox1.Text += "\nException: " + ex.Message.ToString(); }}錯誤消息是“輸入字符串的格式不正確?!蔽蚁嘈艈栴}是試圖將字符串字節(jié)轉(zhuǎn)換為整數(shù)。在 Delphi 中,使用 Ord 函數(shù)很容易。我可能需要從 char 轉(zhuǎn)換為 int。只是不知道如何從字符串中獲取字符。我是 C# 新手。感謝您的任何建議。
2 回答

臨摹微笑
TA貢獻1982條經(jīng)驗 獲得超2個贊
當(dāng)您將字符串轉(zhuǎn)換為 int 時,它會嘗試讀取該字符串,就像它是格式化數(shù)字一樣。但您想要做的是轉(zhuǎn)換字符串中的第一個字節(jié),如下所示:
MsgTypeInt = (int)(MsgText[11]);
注意事項:還沒有編譯或嘗試過這個,也沒有研究從 Encoding.ASCII.GetString 返回每個字符有多少字節(jié)。

至尊寶的傳說
TA貢獻1789條經(jīng)驗 獲得超10個贊
這是將字節(jié)轉(zhuǎn)換為整數(shù)的簡單方法。
class Example {
public static void main(String args[]) {
byte b = 100;
int x;
x = b; // automatic conversion
System.out.println(b+" "+x);
}
}
- 2 回答
- 0 關(guān)注
- 152 瀏覽
添加回答
舉報
0/150
提交
取消