3

Bitwise manipulation and Go newbie here :D I am reading some data from sensor with Go and I get it as 2 bytes - let's say 0xFFFE. It is easy too cast it to uint16 since in Go we can just do uint16(0xFFFE) but what I need is to convert it to integer, because the sensor returns in fact values in range from -32768 to 32767. Now I thought "Maybe Go will be this nice and if I do int16(0xFFFE) it will understand what I want?", but no. I ended up using following solution (I translated some python code from web):

x := 0xFFFE

if (x & (1 << 15)) != 0 {
    x = x - (1<<16)
}

It seems to work, but A) I am not entirely sure why, and B) It looks a bit ugly to what I imagined should be a trivial solution for casting uint16 to int16. Could anyone give me a hand and clarify why this is only way to do this? Or is there any other possible way?

Devligue
  • 413
  • 5
  • 16

1 Answers1

7

But what you want works, "Go is nice":

ui := uint16(0xFFFE)
fmt.Println(ui)
i := int16(ui)
fmt.Println(i)

Output (try it on the Go Playground):

65534
-2

int16(0xFFFE) doesn't work because 0xfffe is an untyped integer constant which cannot be represented by a value of type int16, that's why the the compiler complains. But you can certainly convert any uint16 non-constant value to int16.

See possible duplicates:

Golang: on-purpose int overflow

Does go compiler's evaluation differ for constant expression and other expression

icza
  • 389,944
  • 63
  • 907
  • 827
  • 1
    I have tried it in a bit different form `fmt.Println(int16(uint16(0xFFFE)))` and it throws overflow error. Why does it work in your example then? – Devligue Dec 29 '17 at 13:47
  • 2
    @Devlige Because constant values can only be converted if the type can represent the exact value. In my example I am not converting a constant but a variable, where overflow is allowed (just like in any other language). For an explanation in great details, please check: [Does go compiler's evaluation differ for constant expression and other expression](https://stackoverflow.com/questions/39444852/does-go-compilers-evaluation-differ-for-constant-expression-and-other-expressio/39445372#39445372) – icza Dec 29 '17 at 13:50
  • Perfect! In conclusion Go is nice indeed. It just requires a bit more knowledge :) Thank you – Devligue Dec 29 '17 at 14:05
  • 1
    @kostix Just when I wanted to post the link. That link contains the "more knowledge" regarding constants. – icza Dec 29 '17 at 14:06
  • Seems this is only possible with vars, if writte as one-liner it fails: constant 65534 overflows int16 – andig Oct 09 '18 at 12:56