What is the best way to handle an http resp.Body which is formatted as []uint8 and not as JSON?
I would like to convert the bytes into a float64.
This is the returned value response:
value : %!F([]uint8=[48 46 48 48 49 50 53 53 50 49])
Try using ParseFloat from the strconv package (play):
b := []uint8{48, 46, 48, 48, 49, 50, 53, 53, 50, 49}
f, err := strconv.ParseFloat(string(b), 64)
if err != nil {
// Handle parse error
}
fmt.Printf("%f\n", f) // 0.001255
Related
I could use some help finding all the numbers from a struct array that are above a calculated mean!
//MeanMedianMode struct
type MeanMedianMode struct {
numbers []float64
}
func main() {
// range of numbers
dataType := MeanMedianMode{
numbers: []float64{
84, 25, 88, 56, 10, 19, 11, 80,
45, 83, 22, 40, 22, 52, 61, 13, 73, 23, //Data to be used
90, 89, 6,
},
}
I've figured out how to pass my data easily and find the average as follows...
//CalcMean float64
func (mm *MeanMedianMode) CalcMean() float64 {
total := 0.0
for _, v := range mm.numbers {
total += v
}
return (total / float64(len(mm.numbers)))
//return math.Round(total / float64(len(mm.numbers))) //Should it need to be rounded
}
My biggest issue is replicating that process and using the values stored in the array within another function and iterating over them to find the values greater than (>) the found mean!
I appreciate the insights!
I don't know how you'd like to do it, but something like this I guess:
package main
import (
"fmt"
)
//MeanMedianMode struct
type MeanMedianMode struct {
numbers []float64
}
func main() {
m := &MeanMedianMode{
numbers: []float64{
84, 25, 88, 56, 10, 19, 11, 80,
45, 83, 22, 40, 22, 52, 61, 13, 73, 23,
90, 89, 6,
},
}
mean := m.CalcMean()
for _, n := range m.numbers {
if n > mean {
fmt.Printf("%.3f is greater than the mean\n", n)
}
}
}
//CalcMean float64
func (mm *MeanMedianMode) CalcMean() float64 {
total := 0.0
for _, v := range mm.numbers {
total += v
}
return (total / float64(len(mm.numbers)))
}
CurrentCoordinates []uint8 `json:"current_coordinates"`
type Points struct {
Lat float64 `json:"lat"`
Lng float64 `json:"lng"`
}
DB Column has data as :
POINT(6.887035 79.883757)
From DB i got it into []uint8, then the result is :
[0 0 0 0 1 1 0 0 0 35 161 45 231 82 140 27 64 28 39 133 121 143 248 83 64]
Anyone know how to convert this to coordinates?
The coordinates are stored at the end of your slice, both have 8 bytes which are the little-endian encoded bytes of the IEEE 754 double-precision representation of the floating point numbers.
You may use the encoding/binary package to get the floating-point data of the coordinates as an uint64, and you may use math.Float64frombits() to "convert" that data to float64 type.
This is how you can decode them:
data := []byte{0, 0, 0, 0, 1, 1, 0, 0, 0, 35, 161, 45, 231, 82, 140, 27, 64, 28, 39, 133, 121, 143, 248, 83, 64}
d := binary.LittleEndian.Uint64(data[9:])
x := math.Float64frombits(d)
d = binary.LittleEndian.Uint64(data[17:])
y := math.Float64frombits(d)
fmt.Println(x, y)
This will output (try it on the Go Playground):
6.887035 79.883757
The beginning of your data may be SRID (spatial reference identifier) and/or some kind of distance / accuracy for searches, depends on the database you're using.
Alternatively you may create an io.Reader reading from your slice using bytes.NewReader(), and use the binary.Read() function:
data := []byte{0, 0, 0, 0, 1, 1, 0, 0, 0, 35, 161, 45, 231, 82, 140, 27, 64, 28, 39, 133, 121, 143, 248, 83, 64}
r := bytes.NewReader(data[9:])
var x, y float64
if err := binary.Read(r, binary.LittleEndian, &x); err != nil {
panic(err)
}
if err := binary.Read(r, binary.LittleEndian, &y); err != nil {
panic(err)
}
fmt.Println(x, y)
This will output the same. Try this one on the Go Playground.
I am using Go to implement an algorithm described below:
There is an array,only one number appear one time,all the other numbers appear three times,find the number only appear one time
My code listed below:
import (
"testing"
)
func findBySum(arr []int) int {
result := 0
sum := [32]int{}
for i := 0; i < 32; i++ {
for _, v := range arr {
sum[i] += (v >> uint(i)) & 0x1
}
sum[i] %= 3
sum[i] <<= uint(i)
result |= sum[i]
}
return result
}
func TestThree(t *testing.T) {
// except one nubmer,all other number appear three times
a1 := []int{11, 222, 444, 444, 222, 11, 11, 17, -123, 222, -123, 444, -123} // unqiue number is 17
a2 := []int{11, 222, 444, 444, 222, 11, 11, -17, -123, 222, -123, 444, -123} // unque number is -17
t.Log(findBySum(a1))
t.Log(findBySum(a2))
}
However,I found that the running result in my PC is wrong,and the same code running in https://play.golang.org/p/hEseLZVL617 is correct,I do not know why.
Result in my PC:
Result in https://play.golang.org/p/hEseLZVL617:
As we see,when the unique number is positive,both result are right,but when the unique number is negative,the result in my PC in wrong and the result online is right.
I think it has something to do with the bit operations in my code,but I can't find the root cause.
I used IDEA 2019.1.1 and my Golang version listed below:
I don't know why the same code can works fine online and do not work in my local PC,can anyone help me analysis this? Thanks in advance!
Size of int is platform dependent, it may be 32-bit and it may be 64-bit. On the Go Playground it's 32-bit, on your local machine it's 64-bit.
If we change your example to use int64 explicitly instead of int, the result is the same on the Go Playground too:
func findBySum(arr []int64) int64 {
result := int64(0)
sum := [32]int64{}
for i := int64(0); i < 32; i++ {
for _, v := range arr {
sum[i] += (v >> uint64(i)) & 0x1
}
sum[i] %= 3
sum[i] <<= uint(i)
result |= sum[i]
}
return result
}
func TestThree(t *testing.T) {
// except one nubmer,all other number appear three times
a1 := []int64{11, 222, 444, 444, 222, 11, 11, 17, -123, 222, -123, 444, -123} // unqiue number is 17
a2 := []int64{11, 222, 444, 444, 222, 11, 11, -17, -123, 222, -123, 444, -123} // unque number is -17
t.Log(findBySum(a1))
t.Log(findBySum(a2))
}
You perform bitwise operations that assume 32-bit integer size. To get correct results locally (where your architecture and thus size of int and uint is 64-bit), change all ints to int32 and uint to uint32:
func findBySum(arr []int32) int32 {
result := int32(0)
sum := [32]int32{}
for i := int32(0); i < 32; i++ {
for _, v := range arr {
sum[i] += (v >> uint32(i)) & 0x1
}
sum[i] %= 3
sum[i] <<= uint(i)
result |= sum[i]
}
return result
}
func TestThree(t *testing.T) {
// except one nubmer,all other number appear three times
a1 := []int32{11, 222, 444, 444, 222, 11, 11, 17, -123, 222, -123, 444, -123} // unqiue number is 17
a2 := []int32{11, 222, 444, 444, 222, 11, 11, -17, -123, 222, -123, 444, -123} // unque number is -17
t.Log(findBySum(a1))
t.Log(findBySum(a2))
}
Lesson: if you perform calculations whose result depend on the representation size, always be explicit, and use fixed-size numbers like int32, int64, uint32, uint64.
I have a string, byteArray:
byteArray := []byte("Hello, 世界-123..")
fmt.Println(byteArray)
which looks like:
[72 101 108 108 111 44 32 228 184 150 231 149 140 45 49 50 51 46 46]
I need to get byteArray[0] as a string, like "72", but they're byte type.
How do I achieve this?
You can use strconv.Itoa:
byteArray := []byte("Hello, 世界-123..")
for _, v := range byteArray {
s := strconv.Itoa(int(v))
fmt.Printf("%T, %v\n", s, s)
}
There you go.
byteArray := []byte("Hello, 世界-123..")
fmt.Println(string(byteArray[0]))
// H
Are there any similar libraries/packages in go that emulate what vis(3) and unvis(3) do for BSD systems? I'm trying to do something that requires representation of strings that contain special characters like whitespace and such.
No, Not exactly, but if you are looking for URL encoding, You can do all the URL encoding you want with the net/url package:
see: Encode / decode URLs
and: Is there any example and usage of url.QueryEscape ? for golang
sample code:
fmt.Println(url.QueryEscape("https://stackoverflow.com/questions/tagged/go test\r \r\n"))
output:
http%3A%2F%2Fstackoverflow.com%2Fquestions%2Ftagged%2Fgo+test%0D+%0D%0A
or write your own:
in Go string is UTF-8 encoded, and is in effect a read-only slice of bytes:
you may get bytes like this:
str := "UTF-8"
bytes := []byte(str) // string to slice
fmt.Println(str, bytes) // UTF8 [85 84 70 45 56]
or convert bytes to string like this:
s := string([]byte{85, 84, 70, 45, 56, 32, 0xc2, 0xb5}) // slice to string
fmt.Println(s) // UTF-8 µ
0xC2 0xB5 is UTF-8 (hex) for Character 'MICRO SIGN' (U+00B5) see: http://www.fileformat.info/info/unicode/char/00b5/index.htm
also you may get bytes like this:
for i := 0; i < len(s); i++ {
fmt.Printf("%d: %d, ", i, s[i])
//0: 85, 1: 84, 2: 70, 3: 45, 4: 56, 5: 32, 6: 194, 7: 181,
}
or in compact Hex format:
fmt.Printf("% x\n", s) // 55 54 46 2d 38 20 c2 b5
and get runes (Unicode codepoints) like this:
for i, v := range s {
fmt.Printf("%d: %v, ", i, v)
//0: 85, 1: 84, 2: 70, 3: 45, 4: 56, 5: 32, 6: 181,
}
see: What is a rune?
and convert rune to string:
r := rune(181)
fmt.Printf("%#U\n", r) // U+00B5 'µ'
st := "this is UTF-8: " + string(r)
fmt.Println(st) // this is UTF-8: µ
convert slice of runes to string:
rs := []rune{181, 181, 181, 181}
sr := string(rs)
fmt.Println(sr) // µµµµ
convert string to slice of runes:
br := []rune(sr)
fmt.Println(br) //[181 181 181 181]
The %q (quoted) verb will escape any non-printable byte sequences in a string so the output is unambiguous:
fmt.Printf("%+q \n", "Hello, 世界") // "Hello, \u4e16\u754c"
unicode.IsSpace reports whether the rune is a space character as defined by Unicode's White Space property; in the Latin-1 space this is
'\t', '\n', '\v', '\f', '\r', ' ', U+0085 (NEL), U+00A0 (NBSP).
sample code:
package main
import (
"bytes"
"fmt"
"unicode"
)
func main() {
var buf bytes.Buffer
s := "\u4e16\u754c \u0020\r\n 世界"
for _, r := range s {
if unicode.IsSpace(r) {
buf.WriteString(fmt.Sprintf("\\u%04x", r))
} else {
buf.WriteString(string(r))
}
}
st := buf.String()
fmt.Println(st)
}
output:
世界\u0020\u0020\u000d\u000a\u0020\u0020世界
You can find more functions in the unicode/utf8, unicode, strconv and strings packages:
https://golang.org/pkg/unicode/utf8/
https://golang.org/pkg/unicode/
https://golang.org/pkg/strings/
https://golang.org/pkg/strconv/
https://blog.golang.org/strings