Skip to content

Instantly share code, notes, and snippets.

@julienschmidt
Created October 4, 2015 01:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save julienschmidt/d118836373daf32be3de to your computer and use it in GitHub Desktop.
Save julienschmidt/d118836373daf32be3de to your computer and use it in GitHub Desktop.
Format Bytes human-readable
/*
The MIT License (MIT)
Copyright (c) 2015 Julien Schmidt
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package main
import "fmt"
var (
unitsSI = [...]string{"B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"}
unitsIEC = [...]string{"B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"}
)
func FormatBytesSI(n uint64, fd uint8) string {
var i int
if fd == 0 {
for n >= 1000 {
n /= 1000
i++
}
return fmt.Sprintf("%d %s", n, unitsSI[i])
} else {
f := float64(n)
for f >= 1000 {
f /= 1000
i++
}
return fmt.Sprintf(fmt.Sprintf("%%.0%df %%s", fd), f, unitsSI[i])
}
}
func FormatBytesIEC(n uint64, fd uint8) string {
var i int
if fd == 0 {
for n >= 1024 {
n /= 1024
i++
}
return fmt.Sprintf("%d %s", n, unitsIEC[i])
} else {
f := float64(n)
for f >= 1024 {
f /= 1024
i++
}
return fmt.Sprintf(fmt.Sprintf("%%.0%df %%s", fd), f, unitsIEC[i])
}
}
func main() {
n := uint64(13255555555555513)
fmt.Println(FormatBytesSI(n, 4))
fmt.Println(FormatBytesIEC(n, 4))
}
@julienschmidt
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment