[go-nuts] []byte to int32

1,691 views
Skip to first unread message

kar

unread,
Apr 21, 2010, 4:23:07 AM4/21/10
to golang-nuts
is there a way to convert byte arrays to integer in GO?. here is my
situation, im porting my legacy C program to Go, and in old codes, i
have special integer sizes, int8, int16, (int24 - 3bytes), int32,
(int40 - 5bytes), int64. that way provides some compression to my
internal database format. so when i read a 3-bytes (int24) from the
DB, i need to convert it to int32 for processing. any suggestion on
how to convert this?

thanks in advance.


--
Subscription settings: http://groups.google.com/group/golang-nuts/subscribe?hl=en

Roger Pau Monné

unread,
Apr 21, 2010, 4:28:56 AM4/21/10
to kar, golang-nuts
You could use something like:

number := uint32(byte[0]) | (uint32(byte[1]) << 8) | (uint32(byte[2]) << 16) | ....

The encoding/binary package has some examples.

2010/4/21 kar <akma...@gmail.com>

kar

unread,
Apr 21, 2010, 4:34:18 AM4/21/10
to golang-nuts
good to know i could cast byte directly to int and shift it. thanks

On Apr 21, 4:28 pm, Roger Pau Monné <roy...@gmail.com> wrote:
> You could use something like:
>
> number := uint32(byte[0]) | (uint32(byte[1]) << 8) | (uint32(byte[2]) << 16)
> | ....
>
> The encoding/binary package has some examples.
>
> 2010/4/21 kar <akmal...@gmail.com>
Reply all
Reply to author
Forward
0 new messages