Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert int (int64) into uint16 in golang?

Tags:

go

I can 100% guaranty the value of input int variable is always unsign(positive) and less than int16.

How can I convert this int type variable to uint16?

like image 815
Yi Jiang Avatar asked Mar 22 '16 01:03

Yi Jiang


2 Answers

// convert the type and assign to new variable or pass as a parameter. 
var i int
...
u := uint16(i)
foo(uint16(i))
like image 96
WeakPointer Avatar answered Oct 06 '22 07:10

WeakPointer


You need to check that the number is not negative and that it is <= 0xFFFF and then cast it to an unsigned 16 bit int.

like image 20
MoDJ Avatar answered Oct 06 '22 07:10

MoDJ