Code Monkey home page Code Monkey logo

go-binary-pack's Introduction

Go BinaryPack

Build Status GoDoc

BinaryPack is a simple Golang library which implements some functionality of Python's struct package.

Install

go get github.com/roman-kachanovsky/go-binary-pack/binary-pack

Go mod

require github.com/roman-kachanovsky/go-binary-pack v0.0.0-20170214094030-e260e0dc6732 // indirect

How to use

package main

/*
require github.com/roman-kachanovsky/go-binary-pack v0.0.0-20170214094030-e260e0dc6732 // indirect
 */
import (
	"fmt"
	"reflect"

	. "github.com/roman-kachanovsky/go-binary-pack/binary-pack"
)

func main() {
	// 要编码的结构体字段的数据格式
	format := []string{"I", "?", "d", "6s"}

	// 要打包的数据字段
	values := []interface{}{4, true, 3.14, "Golang"}

	// 创建二进制数据包
	bp := new(BinaryPack)

	// 封装数据到数据包中
	data, _ := bp.Pack(format, values)
	fmt.Printf("编码后:%+v\n", data)


	// 拆包数据到[]interface{}
	unpacked_values, _ := bp.UnPack(format, data)

	if !reflect.DeepEqual(unpacked_values, values) {
		fmt.Printf("Unpacked %v != original %v", unpacked_values, values)
	}
	fmt.Printf("解码后:%+v\n", unpacked_values)

	// 按照格式包来计算二进制包的大小
	size, _ := bp.CalcSize(format)

	if size != len(data) {
		fmt.Printf("Size(%v) != %v", size, len(data))
	}
	fmt.Printf("二进制包字节数:%+v\n", size)
}
/*
编码后:[4 0 0 0 1 31 133 235 81 184 30 9 64 71 111 108 97 110 103]
解码后:[4 true 3.14 Golang]
二进制包字节数:19

 */

go-binary-pack's People

Contributors

roman-kachanovsky avatar terryliu avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.