本文整理汇总了Golang中encoding/hex.Decode函数的典型用法代码示例。如果您正苦于以下问题:Golang Decode函数的具体用法?Golang Decode怎么用?Golang Decode使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Decode函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。
示例1: GetConfig
func (a *ADAM4000) GetConfig() error {
resp, err := a.comResF("$%02X2\r", a.address)
if err != nil {
return err
}
addr := make([]byte, 1)
typecode := make([]byte, 1)
baud := make([]byte, 1)
data := make([]byte, 1)
hex.Decode(addr, resp[1:3])
hex.Decode(typecode, resp[3:5])
hex.Decode(baud, resp[5:7])
hex.Decode(data, resp[7:9])
a.Address = addr[0]
a.InputRange = InputRangeCode(typecode[0])
a.BaudRate = BaudRateCode(baud[0])
fmt.Printf("%X\n", data)
a.Integration_time = data[0]&byte(1<<7) > 0
a.Checksum = data[0]&byte(1<<6) > 0
a.DataFormat = DataFormatCode(data[0] & byte(2))
if a.Address != a.address {
fmt.Printf("Warning: Configured address (%d) differs from connected address (%d), in init mode?\n", a.Address, a.address)
}
return nil
}
开发者ID:thoj,项目名称:go-adam4000,代码行数:28,代码来源:adam4000.go
示例2: SetBytes
func (o *Commit) SetBytes(b []byte) (err error) {
o.Content = b
lines := bytes.Split(b, []byte{'\n'})
for i := range lines {
if len(lines[i]) > 0 {
split := bytes.SplitN(lines[i], []byte{' '}, 2)
switch string(split[0]) {
case "tree":
o.Tree = make([]byte, 20)
_, err = hex.Decode(o.Tree, split[1])
case "parent":
h := make([]byte, 20)
_, err = hex.Decode(h, split[1])
if err == nil {
o.Parents = append(o.Parents, h)
}
case "author":
o.Author = string(split[1])
case "committer":
o.Committer = string(split[1])
}
if err != nil {
return
}
} else {
o.Message = string(bytes.Join(append(lines[i+1:]), []byte{'\n'}))
break
}
}
return
}
开发者ID:linhua55,项目名称:gitchain,代码行数:31,代码来源:objects.go
示例3: UnmarshalText
func (c *Color) UnmarshalText(b []byte) (err error) {
s := string(b)
if s == "none" {
c.RGBA.R = 0x00
c.RGBA.G = 0x00
c.RGBA.B = 0x00
c.RGBA.A = 0x00
return nil
}
var buf [4]byte
switch len(b) {
case 6:
_, err = hex.Decode(buf[:3], b)
buf[3] = 0xFF
case 8:
_, err = hex.Decode(buf[:], b)
default:
return fmt.Errorf("Color.UnmarshalText: expected a hexadecimal string in the form RRGGBB or RRGGBBAA, or \"none\" (not %q)", s)
}
if err != nil {
return fmt.Errorf("Color.UnmarshalText: expected a hexadecimal string in the form RRGGBB or RRGGBBAA, or \"none\" (not %q)", s)
}
c.RGBA.R = buf[0]
c.RGBA.G = buf[1]
c.RGBA.B = buf[2]
c.RGBA.A = buf[3]
return nil
}
开发者ID:kierdavis,项目名称:k12,代码行数:28,代码来源:util.go
示例4: parseColor
func parseColor(colors []string) []dmx.Color {
dmxcolors := make([]dmx.Color, 0, len(colors))
for _, color := range colors {
var data [1]byte
_, err := hex.Decode(data[:], []byte(color[:2]))
if err != nil {
panic(err)
}
r := data[0]
_, err = hex.Decode(data[:], []byte(color[2:4]))
if err != nil {
panic(err)
}
g := data[0]
_, err = hex.Decode(data[:], []byte(color[4:6]))
if err != nil {
panic(err)
}
b := data[0]
dmxcolors = append(dmxcolors, dmx.Color{r, g, b})
}
return dmxcolors
}
开发者ID:uvgroovy,项目名称:dmx,代码行数:25,代码来源:animate.go
示例5: byte_set
func (d *UUID) byte_set(uuid []byte) (err error) {
t_uuid := [16]byte{}
t_d := bytes.Split(uuid, []byte{'-'})
if len(t_d) != 5 {
return errors.New("not a uuid : [" + string(uuid) + "]")
}
if len(t_d[0]) != 8 {
return errors.New("not a uuid : [" + string(uuid) + "]")
}
_, err = hex.Decode(t_uuid[0:4], t_d[0])
if err != nil {
return
}
if len(t_d[1]) != 4 || len(t_d[2]) != 4 || len(t_d[3]) != 4 {
return errors.New("not a uuid : [" + string(uuid) + "]")
}
_, err = hex.Decode(t_uuid[4:6], t_d[1])
if err != nil {
return
}
_, err = hex.Decode(t_uuid[6:8], t_d[2])
if err != nil {
return
}
_, err = hex.Decode(t_uuid[8:10], t_d[3])
if err != nil {
return
}
if len(t_d[4]) != 12 {
return errors.New("not a uuid : [" + string(uuid) + "]")
}
_, err = hex.Decode(t_uuid[10:16], t_d[4])
if err != nil {
return
}
switch t_uuid[6] & 0xf0 {
case UUIDv1, UUIDv2, UUIDv3, UUIDv4, UUIDv5:
default:
return errors.New("unknown version : [" + string(uuid) + "]")
}
switch {
case (t_uuid[8] & 0x80) == UUID_NCS:
case (t_uuid[8] & 0xc0) == UUID_RFC:
case (t_uuid[8] & 0xe0) == UUID_MS:
case (t_uuid[8] & 0xe0) == UUID_UNUSED:
default:
err = errors.New("unknown variant : [" + string(uuid) + "]")
return
}
*d = UUID(t_uuid)
return nil
}
开发者ID:nathanaelle,项目名称:useful.types,代码行数:59,代码来源:uuid.go
示例6: FromString
// Converts a string representation of a UUID into a UUID object.
func FromString(s string) (u UUID, e error) {
if len(s) != UUIDStringLen {
return nil, &BadUUIDStringError{"length is not 36 bytes: " + s}
}
// Make enough space for the storage.
u = make([]byte, UUIDByteLen)
s_byte := []byte(s)
var i int
var err error
i, err = hex.Decode(u[0:4], s_byte[0:8])
if err != nil || i != 4 {
return nil, &BadUUIDStringError{"Invalid first component: " + s}
}
if s_byte[8] != '-' {
return nil, &BadUUIDStringError{"Position 8 is not a dash: " + s}
}
i, err = hex.Decode(u[4:6], s_byte[9:13])
if err != nil || i != 2 {
return nil, &BadUUIDStringError{"Invalid second component: " + s}
}
if s_byte[13] != '-' {
return nil, &BadUUIDStringError{"Position 13 is not a dash: " + s}
}
i, err = hex.Decode(u[6:8], s_byte[14:18])
if err != nil || i != 2 {
return nil, &BadUUIDStringError{"Invalid third component: " + s}
}
if s_byte[18] != '-' {
return nil, &BadUUIDStringError{"Position 18 is not a dash: " + s}
}
i, err = hex.Decode(u[8:10], s_byte[19:23])
if err != nil || i != 2 {
return nil, &BadUUIDStringError{"Invalid fourth component: " + s}
}
if s_byte[23] != '-' {
return nil, &BadUUIDStringError{"Position 23 is not a dash: " + s}
}
i, err = hex.Decode(u[10:16], s_byte[24:36])
if err != nil || i != 6 {
return nil, &BadUUIDStringError{"Invalid fifth component: " + s}
}
if u[8]&0xc0 != 0x80 {
return nil, &BadUUIDStringError{"Reserved bits used: " + s}
}
return u, nil
}
开发者ID:wallyqs,项目名称:util,代码行数:60,代码来源:uuid.go
示例7: SetHex
// SetHex takes two hexidecimal strings and decodes them into the receiver.
func (p *Point) SetHex(x, y string) error {
if len(x) != 64 || len(y) != 64 {
return errors.New("invalid hex string length")
}
if _, err := hex.Decode(p.x[:], []byte(x)); err != nil {
return err
}
_, err := hex.Decode(p.y[:], []byte(y))
return err
}
开发者ID:travis1230,项目名称:RosettaCodeData,代码行数:11,代码来源:bitcoin-public-point-to-address.go
示例8: Authorized
// returns true if the sha256 hex password hash (of $name|$pass)
// stored at $basePath/$name/.password matches the user/pass
// arguements here.
func (a *authorizer) Authorized(name, pass string) bool {
nameCleaned := cleanUser(name)
// basically, if we detect any path manipulation stuff, bail
if len(nameCleaned) == 0 || nameCleaned != name || strings.Index(nameCleaned, "/") != -1 {
return false
}
passwordPath := path.Join(a.basePath, ".auth", nameCleaned)
expectedHashHex, err := ioutil.ReadFile(passwordPath)
if err != nil {
log.Print("reading password file failed: ", err)
return false
}
expectedHash := make([]byte, sha256.Size)
_, err = hex.Decode(expectedHash, expectedHashHex)
if err != nil {
log.Printf("%s: hex.Decode: %s\n", passwordPath, err)
return false
}
// hash the user supplied password
inputHash := sha256.New()
inputHash.Write([]byte(nameCleaned))
inputHash.Write([]byte("|"))
inputHash.Write([]byte(pass))
// and check if it matches the one on disk
return subtle.ConstantTimeCompare(expectedHash, inputHash.Sum(nil)) == 1
}
开发者ID:bpowers,项目名称:goroast,代码行数:32,代码来源:auth.go
示例9: HandleData
func (a authCookieSha1) HandleData(data []byte) ([]byte, AuthStatus) {
challenge := make([]byte, len(data)/2)
_, err := hex.Decode(challenge, data)
if err != nil {
return nil, AuthError
}
b := bytes.Split(challenge, []byte{' '})
if len(b) != 3 {
return nil, AuthError
}
context := b[0]
id := b[1]
svchallenge := b[2]
cookie := a.getCookie(context, id)
if cookie == nil {
return nil, AuthError
}
clchallenge := a.generateChallenge()
if clchallenge == nil {
return nil, AuthError
}
hash := sha1.New()
hash.Write(bytes.Join([][]byte{svchallenge, clchallenge, cookie}, []byte{':'}))
hexhash := make([]byte, 2*hash.Size())
hex.Encode(hexhash, hash.Sum(nil))
data = append(clchallenge, ' ')
data = append(data, hexhash...)
resp := make([]byte, 2*len(data))
hex.Encode(resp, data)
return resp, AuthOk
}
开发者ID:40a,项目名称:bootkube,代码行数:31,代码来源:auth_sha1.go
示例10: NewSimpleSessionManager
//NewSimpleSessionManager returns an instance of seven5.SessionManager.
//This keeps the sessions in memory, not on disk or database but does try to
//insure that sessions are stable across runs by encrypting the session ids
//with a key only the session manager knows. The key must be supplied in
//the environment variable SERVER_SESSION_KEY or this function panics. That
//key should be a 32 character hex string (see key2hex). If you pass nil
//as your generator, we are assuming that you will explicitly connect each
//user session via a call to Assign.
func NewSimpleSessionManager(g Generator) *SimpleSessionManager {
if os.Getenv("SERVER_SESSION_KEY") == "" {
log.Fatalf("unable to find environment variable SERVER_SESSION_KEY")
}
keyRaw := strings.TrimSpace(os.Getenv("SERVER_SESSION_KEY"))
if len(keyRaw) != aes.BlockSize*2 {
log.Fatalf("expected SERVER_SESSION_KEY length to be %d, but was %d", aes.BlockSize*2, len(keyRaw))
}
buf := make([]byte, aes.BlockSize)
l, err := hex.Decode(buf, []byte(keyRaw))
if err != nil {
log.Fatalf("Unable to decode SERVER_SESSION_KEY, maybe it's not in hex? %v", err)
}
if l != aes.BlockSize {
log.Fatalf("expected SERVER_SESSION_KEY decoded length to be %d, but was %d", aes.BlockSize, l)
}
key := buf[0:l]
result := &SimpleSessionManager{
out: make(chan *sessionPacket),
generator: g,
}
go handleSessionChecks(result.out, key)
return result
}
开发者ID:seven5,项目名称:seven5,代码行数:33,代码来源:session.go
示例11: copyBinary
func copyBinary(sourceName, targetName, sourceDir, targetDir string) error {
source := filepath.Join(sourceDir, sourceName)
dest := filepath.Join(targetDir, targetName)
if _, err := os.Stat(source); err != nil {
if os.IsNotExist(err) {
return fmt.Errorf("missing file %s", source)
}
return err
}
if err := CopyFile(source, dest, 0755); err != nil {
return err
}
if b, err := ioutil.ReadFile(source + ".sha256"); err == nil {
if i := bytes.IndexRune(b, ' '); i > 0 {
b = b[:i]
}
expectedHash := make([]byte, hex.DecodedLen(len(b)))
if _, err := hex.Decode(expectedHash, b); err != nil {
return err
}
if err := hashCheck(dest, expectedHash, sha256.New()); err != nil {
return err
}
}
return nil
}
开发者ID:dmcgowan,项目名称:dockerdevtools,代码行数:27,代码来源:copy.go
示例12: DecodePrivateKeyString
func DecodePrivateKeyString(privateKeyString string) [32]byte {
var privateKey [32]byte
_, err := hex.Decode(privateKey[:], []byte(privateKeyString))
checkFatal(err)
return privateKey
}
开发者ID:lgierth,项目名称:cryptoauth,代码行数:7,代码来源:crypto.go
示例13: ParseString
// ParseString converts an UUID in string form to object.
func ParseString(str string) (*UUID, error) {
text := []byte(str)
if len(text) < 32 {
return nil, errors.New("Invalid UUID: ", str)
}
uuid := new(UUID)
b := uuid.Bytes()
for _, byteGroup := range byteGroups {
if text[0] == '-' {
text = text[1:]
}
_, err := hex.Decode(b[:byteGroup/2], text[:byteGroup])
if err != nil {
return nil, err
}
text = text[byteGroup:]
b = b[byteGroup/2:]
}
return uuid, nil
}
开发者ID:v2ray,项目名称:v2ray-core,代码行数:27,代码来源:uuid.go
示例14: UUIDToID
// TODO: leverage a full functional UUID library
func UUIDToID(uuid string) (v ID, err error) {
text := []byte(uuid)
if len(text) < 32 {
err = log.Error("uuid: invalid UUID string: %s", text)
return
}
b := v[:]
for _, byteGroup := range byteGroups {
if text[0] == '-' {
text = text[1:]
}
_, err = hex.Decode(b[:byteGroup/2], text[:byteGroup])
if err != nil {
return
}
text = text[byteGroup:]
b = b[byteGroup/2:]
}
return
}
开发者ID:noah70,项目名称:v2ray-core,代码行数:27,代码来源:id.go
示例15: SignSHA256
// Sign the given hex-endcoded hash checksum and return a Signature
// @@TODO Remove this -- undeeded
func (pk PrivateKey) SignSHA256(hexbytes []byte) (Signature, error) {
if hex.DecodedLen(len(hexbytes)) != sha256.Size {
return nil, ErrPrivateKeySHA256
}
// Decode hex bytes into raw bytes
decodedBytes := make([]byte, hex.DecodedLen(len(hexbytes)))
_, err := hex.Decode(decodedBytes, hexbytes)
if err != nil {
return nil, errors.Wrap(err, ErrPrivateKeySHA256)
}
// Get the rsa cryptokey for signing
cryptoKey, err := pk.GetCryptoKey()
if err != nil {
return nil, errors.Wrap(err, ErrPrivatKeySign)
}
// Compute the signature and return the results
rawSignature, err := rsa.SignPKCS1v15(rand.Reader, cryptoKey, crypto.SHA256, decodedBytes)
if err != nil {
return nil, errors.Wrap(err, ErrPrivatKeySign)
}
return Signature(rawSignature), nil
}
开发者ID:laprice,项目名称:cryptoballot,代码行数:27,代码来源:PrivateKey.go
示例16: NewMemoryDB
func NewMemoryDB(path string) (*MemoryDB, error) {
mem := NewEmptyMemoryDB()
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
r, err := gzip.NewReader(f)
if err != nil {
return nil, err
}
defer r.Close()
scanner := bufio.NewScanner(r)
for scanner.Scan() {
parts := strings.Split(scanner.Text(), ":")
var nodeid data.Hash256
if _, err := hex.Decode(nodeid[:], []byte(parts[0])); err != nil {
return nil, err
}
value, err := hex.DecodeString(parts[1])
if err != nil {
return nil, err
}
node, err := data.ReadPrefix(bytes.NewReader(value), nodeid)
if err != nil {
return nil, err
}
mem.nodes[nodeid] = node
}
if scanner.Err() != nil {
return nil, scanner.Err()
}
return mem, nil
}
开发者ID:Zoramite,项目名称:ripple,代码行数:34,代码来源:mem.go
示例17: startTCP
func startTCP(cb func([]byte)) net.Listener {
listener, err := net.Listen("tcp", ":0")
if err != nil {
log.Fatal("Can't start:", err)
}
go func() {
for {
conn, _ := listener.Accept()
defer conn.Close()
go func() {
reader := bufio.NewReader(conn)
scanner := bufio.NewScanner(reader)
for scanner.Scan() {
encodedPayload := scanner.Bytes()
// Hex encoding always 2x number of bytes
decoded := make([]byte, len(encodedPayload)/2)
hex.Decode(decoded, encodedPayload)
cb(decoded)
}
}()
}
}()
return listener
}
开发者ID:newyue588cc,项目名称:gor,代码行数:29,代码来源:output_tcp_test.go
示例18: decryptSessionId
//given a blob of text to decode, checks a few things and returns either
//the originally given unique id and true or "" and false.
func decryptSessionId(encryptedHex string, block cipher.Block) (string, bool) {
ciphertext := make([]byte, len(encryptedHex)/2)
l, err := hex.Decode(ciphertext, []byte(encryptedHex))
if err != nil {
log.Printf("unable to decode the hex bytes of session id (%s,%d): %v", encryptedHex, len(encryptedHex), err)
return "", false
}
iv := ciphertext[:aes.BlockSize]
stream := cipher.NewCTR(block, iv)
cleartext := make([]byte, l-len(iv))
stream.XORKeyStream(cleartext, ciphertext[aes.BlockSize:])
s := string(cleartext)
if !strings.HasPrefix(s, s5CookiePrefix) {
log.Printf("No cookie prefix found, probably keys changed")
return "", false
}
s = strings.TrimPrefix(s, s5CookiePrefix+":")
parts := strings.Split(s, ",")
if len(parts) != 2 {
log.Printf("Failed to understand parts of session id: %s", s)
return "", false
}
t, err := strconv.ParseInt(parts[1], 10, 64)
if err != nil {
log.Printf("Could not understand expiration time in session id: %s", s)
return "", false
}
expires := time.Unix(t, 0)
if expires.Before(time.Now()) {
return "", false
}
return parts[0], true
}
开发者ID:seven5,项目名称:seven5,代码行数:36,代码来源:session.go
示例19: UnmarshalJSON
// Parse address from raw json data
func (a *Address) UnmarshalJSON(data []byte) error {
if len(data) > 2 && data[0] == '"' && data[len(data)-1] == '"' {
data = data[1 : len(data)-1]
}
if len(data) > 2 && data[0] == '0' && data[1] == 'x' {
data = data[2:]
}
if len(data) != 2*AddressLength {
return fmt.Errorf("Invalid address length, expected %d got %d bytes", 2*AddressLength, len(data))
}
n, err := hex.Decode(a[:], data)
if err != nil {
return err
}
if n != AddressLength {
return fmt.Errorf("Invalid address")
}
a.Set(HexToAddress(string(data)))
return nil
}
开发者ID:Raskal8,项目名称:go-ethereum,代码行数:26,代码来源:types.go
示例20: readInput
func readInput(mem *MemoryDB, path string) error {
f, err := os.Open(path)
if err != nil {
return err
}
defer f.Close()
r, err := gzip.NewReader(f)
if err != nil {
return err
}
defer r.Close()
scanner := bufio.NewScanner(r)
for scanner.Scan() {
parts := strings.Split(scanner.Text(), ":")
var nodeid data.Hash256
if _, err := hex.Decode(nodeid[:], []byte(parts[0])); err != nil {
return err
}
value, err := hex.DecodeString(parts[1])
if err != nil {
return err
}
node, err := data.ReadPrefix(bytes.NewReader(value), nodeid)
if err != nil {
return err
}
mem.nodes[nodeid] = node
}
return scanner.Err()
}
开发者ID:aryaya,项目名称:ripple,代码行数:30,代码来源:mem.go
注:本文中的encoding/hex.Decode函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论