Why can an int hold a negative number?

3,298 views
Skip to first unread message

Po Tatoe

unread,
Nov 18, 2014, 7:32:16 PM11/18/14
to golan...@googlegroups.com

According to the spec (http://golang.org/ref/spec#Numeric_types), an 'int' is same as a 'uint', meaning an unsigned integer, either 32 or 64 bits, so either:

uint32      the set of all unsigned 32-bit integers (0 to 4294967295)
uint64      the set of all unsigned 64-bit integers (0 to 18446744073709551615)

"0 to 4294967295" would seem to imply no negative values, but this works just fine:

package main

import "fmt"

func main() {
var foo int
foo = -1 // works fine!

fmt.Println(foo) // => -1
}

So my question is: why can an int store a negative number?  Please be gentle - I'm new to typed languages and golang.



Dan Kortschak

unread,
Nov 18, 2014, 7:35:09 PM11/18/14
to Po Tatoe, golan...@googlegroups.com
Same size, not same range.

Matthew Kane

unread,
Nov 18, 2014, 7:35:09 PM11/18/14
to Po Tatoe, golang-nuts

It's the same SIZE only. int and uint are the same SIZE on a given platform.

Sent from my mobile.

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Dave Cheney

unread,
Nov 18, 2014, 7:37:42 PM11/18/14
to golan...@googlegroups.com


On Wednesday, 19 November 2014 11:32:16 UTC+11, Po Tatoe wrote:

According to the spec (http://golang.org/ref/spec#Numeric_types), an 'int' is same as a 'uint', meaning an unsigned integer, either 32 or 64 bits, so either:

The spec says "int is the same size as uint", where size refers to the number of bytes of memory (and thus bits) used to represent the integer. int is signed, uint is unsigned, the former can represent negative numbers as well as positive numbers, at the cost of one bit's resolution, the latter can only represent non negative numbers, but can count twice as high as int.

Po Tatoe

unread,
Nov 18, 2014, 7:50:10 PM11/18/14
to golan...@googlegroups.com

Thanks Dave, and the other folks that replied.

andrewc...@gmail.com

unread,
Nov 18, 2014, 8:00:13 PM11/18/14
to golan...@googlegroups.com
As was mentioned, both are the same size in memory. To elaborate: in "int" the values represent twos complement numbers http://en.wikipedia.org/wiki/Two%27s_complement. For 32 bit int the value 0xffffffff is -1  but the same value is 4294967295 for a 32 bit uint. It just controls how the computer interprets the values.

So for example, if you could see the bits, the expression 0xffffffff > 0x00000000 is true or false depending on whether it is comparing uint values or int values.
Reply all
Reply to author
Forward
0 new messages