dongxuxian6930 2014-03-17 04:57
浏览 491
已采纳

Golang上的十六进制总和

Thanks for reading my question. I am trying to count ASTM checksum on Golang but couldn't figure it out how to convert string or byte to hexadecimal that is countable by myself and Google. Please let me request help, thanks.

At Golang, how to convert a character to hexadecimal that can allow performing a sum?

Example:

// Convert character "a" to hex 0x61 ( I understand this will not work for my case as it became a string.)
hex := fmt.Sprintf("%x","a")
// sum the 0x61 with 0x01 so it will become 0x62 = "b"
fmt.Printf("%v",hex + 0x01)

Thank you so much and please have a nice day.

Thanks for everyone answering my question! peterSO and ANisus answers both solved my problem. Please let me choose ANisus's reply as answer as it including ASTM special character in it. I wish StackOverflow could choose multiple answers. Thanks for everybody answering me and please have a nice day!

  • 写回答

4条回答 默认 最新

  • duanma8207 2014-03-17 05:25
    关注

    Intermernet's answer shows you how to convert a hexadecimal string into an int value.

    But your question seems to suggest that you want to want to get the code point value of the letter 'a' and then do aritmetics on that value. To do this, you don't need hexadecimal. You can do the following:

    package main
    
    import "fmt"
    
    func main() {
        // Get the code point value of 'a' which is 0x61
        val := 'a'
    
        // sum the 0x61 with 0x01 so it will become 0x62 = 'b'
        fmt.Printf("%v", string(val + 0x01))
    }
    

    Result:

    b

    Playground: http://play.golang.org/p/SbsUHIcrXK

    Edit:

    Doing the actual ASTM checksum from a string using the algorithm described here can be done with the following code:

    package main
    
    import (
        "fmt"
    )
    
    const (
        ETX = 0x03
        ETB = 23
        STX = 0x02
    )
    
    func ASTMCheckSum(frame string) string {
    
        var sumOfChars uint8
    
        //take each byte in the string and add the values
        for i := 0; i < len(frame) ; i++ {      
            byteVal := frame[i]
            sumOfChars += byteVal
    
            if byteVal == STX {
                sumOfChars = 0
            }
    
            if byteVal == ETX || byteVal == ETB {
                break
            }
        }
    
        // return as hex value in upper case
        return fmt.Sprintf("%02X", sumOfChars)
    }
    
    func main() {
        data := "\x025R|2|^^^1.0000+950+1.0|15|||^5^||V||34001637|20080516153540|20080516153602|34001637\x033D
    "
        //fmt.Println(data)
        fmt.Println(ASTMCheckSum(data))
    }
    

    Result:

    3D

    Playground: http://play.golang.org/p/7cbwryZk8r

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?