Reputation: 344
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)
Upvotes: 1
Views: 83
Reputation:
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.
1 int
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
).
Upvotes: 2
Reputation: 3549
You need to make "var sum" an "uint16", otherwise it'll never go above 00FF.
Upvotes: 4