duanbichenhe1968
2017-12-29 19:52
浏览 175
已采纳

如何验证字符串是否代表十六进制数字

This mostly works:

import "encoding/hex"

func isHexString(s string) bool {
    _, err := hex.DecodeString(s)
    return err == nil
}

However, we also may want to support odd length hex strings. Checking against hex.ErrLength doesn't work because this error precedes whether the string contains hex characters. I guess could manipulate string to contain the appropriate number of characters and apply both checks but it seems like there should be better way.

https://golang.org/pkg/encoding/hex/#DecodeString

图片转代码服务由CSDN问答提供 功能建议

这通常有效:

  import“ encoding / hex”  
 
func isHexString(s string)bool {
 _,err:= hex.DecodeString(s)
 return err == nil 
} 
   
 
 

但是,我们也可能希望支持奇数长度的十六进制字符串。 检查hex.ErrLength不起作用,因为此错误先于字符串是否包含十六进制字符。 我猜可能可以操纵字符串以包含适当数量的字符并应用这两项检查,但似乎应该有更好的方法。

https://golang.org/pkg/encoding/hex/#DecodeString

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douyong1908 2017-12-29 20:01
    已采纳

    If your goal is to parse the hex digits as a integer or unsigned integer, then call strconv.ParseInt or strconv.ParseUint:

    n, err := strconv.ParseUint(s, 16, 64)
    if err != nil {
        // s is not a valid
    }
    
    点赞 打赏 评论

相关推荐 更多相似问题