1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // This package implements hexadecimal encoding and decoding.
13 const hextable = "0123456789abcdef"
15 // EncodedLen returns the length of an encoding of n source bytes.
16 func EncodedLen(n int) int { return n * 2 }
18 // Encode encodes src into EncodedLen(len(src))
19 // bytes of dst. As a convenience, it returns the number
20 // of bytes written to dst, but this value is always EncodedLen(len(src)).
21 // Encode implements hexadecimal encoding.
22 func Encode(dst, src []byte) int {
23 for i, v := range src {
24 dst[i*2] = hextable[v>>4]
25 dst[i*2+1] = hextable[v&0x0f]
31 // OddLengthInputError results from decoding an odd length slice.
32 type OddLengthInputError struct{}
34 func (OddLengthInputError) String() string { return "odd length hex string" }
36 // InvalidHexCharError results from finding an invalid character in a hex string.
37 type InvalidHexCharError byte
39 func (e InvalidHexCharError) String() string {
40 return "invalid hex char: " + strconv.Itoa(int(e))
44 func DecodedLen(x int) int { return x / 2 }
46 // Decode decodes src into DecodedLen(len(src)) bytes, returning the actual
47 // number of bytes written to dst.
49 // If Decode encounters invalid input, it returns an OddLengthInputError or an
50 // InvalidHexCharError.
51 func Decode(dst, src []byte) (int, os.Error) {
53 return 0, OddLengthInputError{}
56 for i := 0; i < len(src)/2; i++ {
57 a, ok := fromHexChar(src[i*2])
59 return 0, InvalidHexCharError(src[i*2])
61 b, ok := fromHexChar(src[i*2+1])
63 return 0, InvalidHexCharError(src[i*2+1])
68 return len(src) / 2, nil
71 // fromHexChar converts a hex character into its value and a success flag.
72 func fromHexChar(c byte) (byte, bool) {
74 case '0' <= c && c <= '9':
76 case 'a' <= c && c <= 'f':
77 return c - 'a' + 10, true
78 case 'A' <= c && c <= 'F':
79 return c - 'A' + 10, true
85 // EncodeToString returns the hexadecimal encoding of src.
86 func EncodeToString(src []byte) string {
87 dst := make([]byte, EncodedLen(len(src)))
92 // DecodeString returns the bytes represented by the hexadecimal string s.
93 func DecodeString(s string) ([]byte, os.Error) {
95 dst := make([]byte, DecodedLen(len(src)))
96 _, err := Decode(dst, src)