add itobytes by qinyif · Pull Request #1 · bytesconv/bytesconv · GitHub
Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
2 changes: 1 addition & 1 deletion LICENSE
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
MIT License

Copyright (c) 2020 bytesconv
Copyright (c) 2020 qinyif

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
Expand Down
17 changes: 15 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,15 @@
# bytesconv
bytesconv
# Package bytesconv

import "https://github.com/bytesconv/bytesconv"

## Overview

Package bytesconv implements conversions to and from bytes representations of basic data types.

## Numeric Conversions

The most common numeric conversions are Bytestoi ([]byte to int) and ItoBytes (int to []byte).

i, err := bytesconv.Bytestoi([]byte("-42"))
bytes := bytesconv.Itobytes(-42)

6 changes: 6 additions & 0 deletions bytestoi.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package bytesconv

func Bytestoi(bytes []byte) int {

return 1
}
68 changes: 68 additions & 0 deletions itobytes.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package bytesconv

import (
"strconv"
)

// Int8ToBytes returns the extended buffer of i in the given base,
func Int8ToBytes(i int8) []byte {
dst := make([]byte, 0, 4)

return strconv.AppendInt(dst, int64(i), 10)
}

func Int16ToBytes(i int32) []byte {
dst := make([]byte, 0, 6)

return strconv.AppendInt(dst, int64(i), 10)
}

func Itobytes(i int) []byte {
if strconv.IntSize == 64 {
return Int64ToBytes(int64(i))
}
return Int32ToBytes(int32(i))
}

func Int32ToBytes(i int32) []byte {
dst := make([]byte, 0, 11)

return strconv.AppendInt(dst, int64(i), 10)
}

func Int64ToBytes(i int64) []byte {
dst := make([]byte, 0, 20)

return strconv.AppendInt(dst, i, 10)
}

func Uint8ToBytes(i uint8) []byte {
dst := make([]byte, 0, 4)

return strconv.AppendUint(dst, uint64(i), 10)
}

func Uint16ToBytes(i uint16) []byte {
dst := make([]byte, 0, 6)

return strconv.AppendUint(dst, uint64(i), 10)
}

func Uint32ToBytes(i uint32) []byte {
dst := make([]byte, 0, 11)

return strconv.AppendUint(dst, uint64(i), 10)
}

func Uint64ToBytes(i uint64) []byte {
dst := make([]byte, 0, 20)

return strconv.AppendUint(dst, i, 10)
}

func UintToBytes(i uint) []byte {
if strconv.IntSize == 64 {
return Uint64ToBytes(uint64(i))
}
return Uint32ToBytes(uint32(i))
}
90 changes: 90 additions & 0 deletions itobytes_test.go