dongxia19772008 2018-08-19 13:07
浏览 77
已采纳

将简单的哈希函数从c转换为go

I'm trying to to convert a simple hash-function from C to Go.

What is the difference between these C and Go scripts and how do I fix the Go code?

C -> Results in {FB;01;4C|64:KDY;KMT;KYR;KT0;TKK;PAC;UD01;UD02;UD03;ID01;ID02;ID03;SYS|124A}

int   sum;
char* pChar;
char  s[8];

msg = "{FB;01;4C|64:KDY;KMT;KYR;KT0;TKK;PAC;UD01;UD02;UD03;ID01;ID02;ID03;SYS|"
sum = 0;
pChar = msg + 1; // sum starts after the opening {
while (*pChar != 0) {
  sum += (int)*pChar++;
}
sprintf(s, "%04X}", sum);
strcat(msg, s);

Go -> Results in {FB;01;4C|64:KDY;KMT;KYR;KT0;TKK;PAC;UD01;UD02;UD03;ID01;ID02;ID03;SYS|004A}

msg := "{FB;01;4C|64:KDY;KMT;KYR;KT0;TKK;PAC;UD01;UD02;UD03;ID01;ID02;ID03;SYS|"
var sum uint8
for i := 1; i < len(msg); i++ {
    sum += msg[i]
}
s := fmt.Sprintf("%04X}", sum)
req := strings.Join([]string{msg, s}, "")
fmt.Println(req)
  • 写回答

2条回答 默认 最新

  • douxunwei7083 2018-08-19 14:29
    关注

    In your C code, the type of sum is int, which is a signed integer type at least 16 bits in size1.

    However, the type of sum is uint8 in your Go code, an unsigned integer type limited to 8 bits.

    Judging by your format string %04X}, you probably are wanting a 16-bit value.

    To fix the Go code, just change uint8 to int and use sum += int(msg[i]) to make the compiler happy. If you want to keep the value of sum strictly 16-bit, you could use uint16 instead and sum += uint16(msg[i]).

    If you're wondering why you need to wrap msg[i] in uint16(...), it's because you're converting the value to a different type. C has "integer promotion" rules that automatically convert a value that has a width less than int to a value of type int. Go, however, has no such rules and simply refuses to compile, stating that the types are incompatible.


    By the way, you could simply do this in your Go code due to its automatic memory management:

    req := msg + fmt.Sprintf("%04X}", sum)
    fmt.Println(req)
    

    or even:

    s := fmt.Sprintf("%04X}", sum)
    fmt.Println(msg + sum)
    

    Nothing wrong with your current approach; it's just extra verbose.


    1int is required to be at least 16-bit in C and at least 32-bit in Go, but it is commonly 32-bit these days in both languages. You should be aware, however, that it could be 64-bit on some current systems and could very well be 64-bit by default at some point in the future for either language; they're not required to keep their data type sizes synchronized. You should keep this in mind when adding the values in msg to ensure the value of sum is 16-bit (or just use uint16).

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

报告相同问题?

悬赏问题

  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计