If I'm right in C++ the LSB is the last bit and determines the sign of the integer. So for example in case of a 8 bit 1111 1111 will be -127 and 1111 1110 will be 127. Please correct me if I'm wrong, but it's not related.
I would check fir the sign of the integer in Go, so I wrote the following:
func signCheck(n int8) {
var sign int8 = 1<<7
if n&sign == 1 {
fmt.Printf("%d is odd - %b\n", n, n)
} else {
fmt.Printf("%d is even - %b\n", n, n)
}
}
This will print out "constant 128 overflows int8", but that make sense because because there is only 7 bit used for determine a number. So I modified as follow:
func signCheck(n int8) {
if n&1<<7 == 1 {
fmt.Printf("%d is odd - %b\n", n, n)
} else {
fmt.Printf("%d is even - %b\n", n, n)
}
}
In this case I don't have to say it's an int8 but I tested it with -127 and 127 and got the following prints:
-127 is even - -1111111
127 is even - 1111111
So in that case how should I check for the sign? go version go1.13.1 linux/amd64
To represent negative integers, Go (and I believe C++ too like most languages) uses the 2's complement format and standard.
In 2's complement the highest bit (MSB) will be 1
if the number is negative, and 0
otherwise.
In Go you can't use a 0x80
typed constant having int8
as its type, because that's outside of its valid range.
You may however convert int8
to uint8
"losslessly", and then you may do so.
Also, when you're masking the 0x80
bit, you have to compare the result to 0x80
, because x & 0x80
can never result in 1
, only in 0
or 0x80
.
func signCheck(n int8) {
if uint8(n)&0x80 == 0x80 {
fmt.Printf("%d is negative - %b\n", n, n)
} else {
fmt.Printf("%d is non-negative - %b\n", n, n)
}
}
Another option is to compare the masking result to 0
:
if uint8(n)&0x80 != 0 { }
Both solutions give the output (try them on the Go Playground):
-127 is negative - -1111111
127 is non-negative - 1111111