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 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记