将char转换回整数

时间:2014-07-18 15:07:47

标签: .net vb.net

当我做转换时,我会做以下编码,

Dim stx As integer = &H82

我知道ASCii通常是0x02,但在我的情况下,实际数据只有7位,MSB总是由' 1'填充,这就是为什么= 0x02 - >为0x82。这会导致以下麻烦。

tx_buff = Chr(stx) 'put stx into buffer prepare to send out

'convert stx back to integer
rx_buff = Asc(Chr(stx)) 

'当转换回来时,rx_buff实际上是0x3F而不是0x82,我想这是因为Chr()函数将& H82转换为UTF-16编码,这是BREAK PERMITTED HERE(U + 0082),但是转换回来时,使用Asc()使用ASCii表,0x3F是?(问号)。

我的问题是如何解决这个问题?谢谢!

2 个答案:

答案 0 :(得分:1)

作为如何发送数据的示例:

Option Infer On
Module Module1

    Const STX As Byte = &H2
    Const ETX As Byte = &H3

    Sub SendByte(b As Byte)
        ' set the msb before sending the byte
        ' code here to send (b OR &H80)
    End Sub

    Sub SendMessage(msgBytes() As Byte)
        ' assumes all messages to be sent start with STX and end with ETX
        SendByte(STX)
        For i = 0 To msgBytes.Length - 1
            SendByte(msgBytes(i))
        Next
        SendByte(ETX)

    End Sub

    Sub SendMessage(msg As String)
        ' For characters with the msb set, this will give &H3F -
        ' so don't use such characters.
        Dim bytesToSend = System.Text.Encoding.ASCII.GetBytes(msg)
        SendMessage(bytesToSend)

    End Sub

    Sub Main()
        ' if the data to send should be represented in ASCII
        Dim messageToSend = "J123"
        SendMessage(messageToSend)

        ' if the "J" should be sent as its ASCII representation but
        '  the following data should be bytes
        Dim bytesMessage() As Byte = {Asc("J"), 1, 2, 3}
        SendMessage(bytesMessage)

    End Sub

End Module

当您收到数据时,请使用

receivedByte = receivedByte And &H7F

取消设置msb。

答案 1 :(得分:0)

根据您的定义;

Dim stx As Byte = &H82   ' 7-bit encoded
Dim etx As Byte = &H83   ' ditto

我认为你应该使用Byte数组传送给++;使用Dim tx_buff() = {stx, &H1, &H2, &H3, etx} 数组;

Byte

当它返回时,再次作为Dim rx_buff(4) As String For vIndex = 0 To tx_Buff.Length - 1 rx_buff(vIndex) = tx_Buff.ToString("X2") Next Console.WriteLine(String.Join(" ", rx_Buff)) 数组,它只需要转换为int / asc / hex或任何要显示的内容(对于这个例子,我只是再现Tx缓冲区);

{{1}}

注意:所有未经测试!随意扩展您的问题,我会相应地更新此答案。