Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encoding with little endianness Go lang

I am having to work on a web server for work and there are portions of our code written by our chief engineers that I don't understand and am currently trying to decipher. Here is a similar and much simpler version of what is happening within our code base, and I was wondering if anyone could give me a deep explanation of what this is doing step by step.

package main
import "fmt"
import "encoding/binary"
func main() {
////////////////////////////////// no need to explain anything
    b := []byte{2,3,5,7,11,13} /// within this comment block.
    for _,e := range b {        //
    fmt.Printf("%d ",e)         //
    }                           //
    fmt.Printf("\n")            //
    //////////////////////////////
    length:= binary.LittleEndian.Uint32(b)  /// <<< Why this results in                                                 
                                            /// 117768962 is the question.
    fmt.Printf("customLen=%d\n",int(length))

}
like image 570
alm2022 Avatar asked Nov 29 '22 08:11

alm2022


1 Answers

When we write numbers in English, we write them in big-endian base-10 representation. For example the number "4567" is understood to mean 4*10^3 + 5*10^2 + 6*10^1 + 7*10^0. This is base-10 because each written digit differs in significance by a factor of 10 from adjacent digits, and it is big-endian because the first written digit is associated with the biggest power of 10.

The same number 4567 could be written in little-endian base-10 as "7654", which in little-endian representation would mean 7*10^0 + 6*10^1 + 5*10^2 + 4*10^3, numerically the same as in the previous paragraph. This is little-endian because the first written digit is associated with the littlest power of 10.

The binary.LittleEndian.Uint32 function receives a slice of bytes and reads out of it a 32-bit unsigned integer represented in little-endian base-256.

So if the base-256 digits in the input slice b are 2,3,5,7 as they are in your code, the little-endian base-256 interpretation of those bytes is 2*256^0 + 3*256^1 + 5*256^2 + 7*256^3. The same number written in big-endian base-10 (which is what fmt.Printf will show you) is "117768962".

like image 199
dtolnay Avatar answered Dec 04 '22 13:12

dtolnay