Convert hex to alphabet - string

How do I obtain the alphabet value from the hex value in Go?
package main
import (
"encoding/hex"
"fmt"
)
func main() {
a := []byte{0x61}
c := hex.Dump(a)
fmt.Println(c,a)
}
http://play.golang.org/p/7iAs2kKw5v

You could use a fmt.Printf() format (example):
func main() {
a := []byte{0x61}
c := hex.Dump(a)
fmt.Printf("'%+v' -- '%s'\n", c, a)
}
Output:
'00000000 61 |a|
' -- 'a'
The %s format is enough to convert the 0x61 in 'a'.

Your question is a little misleading.
Based on your question what you really want is convert a byte value or a []byte (byte slice) to a string or character (which is more or less a rune in Go).
Henceforth I will separate the single byte value from the []byte using these variables:
b := byte(0x61)
bs := []byte{b}
To convert it to a string, you can simply use a conversion which is the cleanest and most simple:
s := string(bs)
If you want it as a "character", you can convert it to a rune:
r := rune(b)
Another solution is using fmt.Printf() as mentioned in VonC's answer and using the %s verb which is:
%s the uninterpreted bytes of the string or slice
You might want to take a look at these alternatives:
%c the character represented by the corresponding Unicode code point
%q a single-quoted character literal safely escaped with Go syntax.
%q accepts both a byte, []byte and rune.
See this litte example to demonstrate these (try it on the Go Playground):
b := byte(0x61)
bs := []byte{b}
fmt.Printf("%s\n", bs)
fmt.Printf("%c\n", b)
fmt.Println(string(bs))
fmt.Printf("%q\n", bs)
fmt.Printf("%q\n", b)
fmt.Printf("%q\n", rune(b))
Output:
a
a
a
"a"
'a'
'a'
If you need the result as a string, you can use the fmt.Sprintf() variant mentioned in satran's answer like this:
s := fmt.Sprintf("%s", bs)
But it's easier to just use the string conversion (string(bs)).

If you just want the string you can you fmt.Sprintf.
package main
import (
"fmt"
)
func main() {
a := []byte{0x61}
c := fmt.Sprintf("%s", a)
fmt.Println(c)
}

Related

How can I iterate over each 2 consecutive characters in a string in go?

I have a string like this:
package main
import "fmt"
func main() {
some := "p1k4"
for i, j := range some {
fmt.Println()
}
}
I want take each two consecutive characters in the string and print them. the output should like p1, 1k, k4, 4p.
I have tried it and still having trouble finding the answer, how should I write the code in go and get the output I want?
Go stores strings in memory as their UTF-8 encoded byte sequence. This maps ASCII charactes one-to-one in bytes, but characters outside of that range map to multiple bytes.
So I would advise to use the for range loop over a string, which ranges over the runes (characters) of the string, properly decoding multi-byte runes. This has the advantage that it does not require allocation (unlike converting the string to []rune). You may also print the pairs using fmt.Printf("%c%c", char1, char2), which also will not require allocation (unlike converting runes back to string and concatenating them).
To learn more about strings, characters and runes in Go, read blog post: Strings, bytes, runes and characters in Go
Since the loop only returns the "current" rune in the iteration (but not the previous or the next rune), use another variable to store the previous (and first) runes so you have access to them when printing.
Let's write a function that prints the pairs as you want:
func printPairs(s string) {
var first, prev rune
for i, r := range s {
if i == 0 {
first, prev = r, r
continue
}
fmt.Printf("%c%c, ", prev, r)
prev = r
}
// Print last pair: prev is the last rune
fmt.Printf("%c%c\n", prev, first)
}
Testing it with your input and with another string that has multi-byte runes:
printPairs("p1k4")
printPairs("Go-世界")
Output will be (try it on the Go Playground):
p1, 1k, k4, 4p
Go, o-, -世, 世界, 界G
package main
import (
"fmt"
)
func main() {
str := "12345"
for i := 0; i < len(str); i++ {
fmt.Println(string(str[i]) + string(str[(i+1)%len(str)]))
}
}
This is a simple for loop over your string with the first character appended at the back:
package main
import "fmt"
func main() {
some := "p1k4"
ns := some + string(some[0])
for i := 0; i < len(ns)-1; i++ {
fmt.Println(ns[i:i+2])
}
}

Converting unicode to "java

I have this a problem with character conversion. It all starts with this string: U+1F618. According to fileformat.info, this string is now (almost) in the HTML Entity (hex) notation.
But I need this character to be converted into a C/C++/Java source code-notation. I really don't know if this is the official name for the notation, but I assume this site to be correct :).
So basically my question is, instead of outputting to the real emoji, how can I get the value \uD83D\uDE18?
package main
import (
"fmt"
"html"
"strconv"
"strings"
)
func main() {
original := "\\U0001f618"
// Hex String
h := strings.ReplaceAll(original, "\\U", "0x")
// Hex to Int
i, _ := strconv.ParseInt(h, 0, 64)
// Unescape the string (HTML Entity -> String).
str := html.UnescapeString(string(i))
// Display the emoji.
fmt.Println(str)
// but I want something like this: \uD83D\uDE18
}
If you have the input as a string, e.g.
s := "\\U0001f618"
You may use strconv.Unquote() to unquote it. Be sure the string you pass to it is quoted (it must be wrapped with backticks or double quotes):
s2, err := strconv.Unquote(`"` + s + `"`)
fmt.Println(s2, err)
This will give you an s2 string that contains your emoji:
😘 <nil>
Java's string model is a char[] which contains the UTF-16 code points. Go's memory model of string is the UTF-8 encoded byte sequence.
To convert a Go string to UTF-16, you may use the unicode/utf16 package of the standard lib. For example utf16.Encode() encodes a series of runes (unicode codepoints) to UTF-16. You get a series of runes from a Go string with a simple type conversion: []rune("some string").
u16 := utf16.Encode([]rune(s2))
fmt.Printf("%X\n", u16)
The above prints the UTF16 codepoints in hexadecimal format:
[D83D DE18]
To get the format you want, use this loop:
buf := &strings.Builder{}
for _, v := range u16 {
fmt.Fprintf(buf, "\\u%X", v)
}
fmt.Println(buf.String())
Which outputs:
\uD83D\uDE18
Try the examples on the Go Playground.
You can capture this series of conversions in a function:
func convert(s string) (string, error) {
s2, err := strconv.Unquote(`"` + s + `"`)
if err != nil {
return "", err
}
buf := &strings.Builder{}
for _, v := range utf16.Encode([]rune(s2)) {
fmt.Fprintf(buf, "\\u%X", v)
}
return buf.String(), nil
}
Using it:
fmt.Println(convert("\\U0001f618"))
Which outputs (try it on the Go Playground):
\uD83D\uDE18 <nil>

How to efficiently convert a string to a byte slice, including the final 0, in Go?

I would like to convert a string to a byte slice, including the final 0 char.
I am aware that the following code converts a string to a slice :
my_slice := []byte("abc")
And that the following code can add the final 0 char:
my_slice = append(my_slice , 0)
But I wonder if it can be done more efficiently, maybe in 1 line, since both lines will allocate memory.
Inefficient example: https://play.golang.org/p/Rg6ri3H66f9
Allocate a slice of the desired length. Copy the string to the slice.
s := "abc"
my_slice := make([]byte, len(s)+1)
copy(my_slice, s)
There's no need to set the last element to zero because make returns a slice with all elements set to zero.
An efficient, one-line method is a function call that is inlined. For example,
package main
import "fmt"
func cstring(s string) []byte {
b := make([]byte, len(s)+1)
copy(b, s)
return b
}
func main() {
s := "abc"
fmt.Printf("%q\n", s)
c := cstring(s) // inlining call to cstring
fmt.Printf("%q\n", c)
}
optimization decisions:
$ go tool compile -m cstring.go
cstring.go:5:6: can inline cstring
cstring.go:15:14: inlining call to cstring
cstring.go:6:11: make([]byte, len(s) + 1) escapes to heap
cstring.go:5:14: cstring s does not escape
cstring.go:13:13: s escapes to heap
cstring.go:15:14: make([]byte, len(s) + 1) escapes to heap
cstring.go:17:13: c escapes to heap
cstring.go:13:12: main ... argument does not escape
cstring.go:17:12: main ... argument does not escape
$
Output:
$ go run cstring.go
"abc"
"abc\x00"
$
Playground: https://play.golang.org/p/7gi9gR7iWkS

Golang converting from rune to string

I have the following code, it is supposed to cast a rune into a string and print it. However, I am getting undefined characters when it is printed. I am unable to figure out where the bug is:
package main
import (
"fmt"
"strconv"
"strings"
"text/scanner"
)
func main() {
var b scanner.Scanner
const a = `a`
b.Init(strings.NewReader(a))
c := b.Scan()
fmt.Println(strconv.QuoteRune(c))
}
That's because you used Scanner.Scan() to read a rune but it does something else. Scanner.Scan() can be used to read tokens or runes of special tokens controlled by the Scanner.Mode bitmask, and it returns special constants form the text/scanner package, not the read rune itself.
To read a single rune use Scanner.Next() instead:
c := b.Next()
fmt.Println(c, string(c), strconv.QuoteRune(c))
Output:
97 a 'a'
If you just want to convert a single rune to string, use a simple type conversion. rune is alias for int32, and converting integer numbers to string:
Converting a signed or unsigned integer value to a string type yields a string containing the UTF-8 representation of the integer.
So:
r := rune('a')
fmt.Println(r, string(r))
Outputs:
97 a
Also to loop over the runes of a string value, you can simply use the for ... range construct:
for i, r := range "abc" {
fmt.Printf("%d - %c (%v)\n", i, r, r)
}
Output:
0 - a (97)
1 - b (98)
2 - c (99)
Or you can simply convert a string value to []rune:
fmt.Println([]rune("abc")) // Output: [97 98 99]
There is also utf8.DecodeRuneInString().
Try the examples on the Go Playground.
Note:
Your original code (using Scanner.Scan()) works like this:
You called Scanner.Init() which sets the Mode (b.Mode) to scanner.GoTokens.
Calling Scanner.Scan() on the input (from "a") returns scanner.Ident because "a" is a valid Go identifier:
c := b.Scan()
if c == scanner.Ident {
fmt.Println("Identifier:", b.TokenText())
}
// Output: "Identifier: a"
I know I'm a bit late to the party but here's a []rune to string function:
func runesToString(runes []rune) (outString string) {
// don't need index so _
for _, v := range runes {
outString += string(v)
}
return
}
yes, there is a named return but I think it's ok in this case as it reduces the number of lines and the function is only short
This simple code works in converting a rune to a string
s := fmt.Sprintf("%c", rune)
Since I came to this question searching for rune and string and char, thought this may help newbies like me
// str := "aഐbc"
// testString(str)
func testString(oneString string){
//string to byte slice - No sweat -just type cast it
// As string IS A byte slice
var twoByteArr []byte = []byte(oneString)
// string to rune Slices - No sweat
// string IS A slice of runes
var threeRuneSlice []rune = []rune(oneString)
// Hmm! String seems to have a dual personality it is both a slice of bytes and
// a slice of runes - yeah - read on
// A rune slice can be convered to string -
// No sweat - as string == rune slice
var thrirdString string = string(threeRuneSlice)
// There is a catch here and that is in printing "characters", using for loop and range
fmt.Println("Chars in oneString")
for i,r := range oneString {
fmt.Printf(" %d %v %c ",i,r,r) //you may not get index 0,1,2,3 here
// since the range runs specially over strings https://blog.golang.org/strings
}
fmt.Println("\nChars in threeRuneSlice")
for i,r := range threeRuneSlice {
fmt.Printf(" %d %v %c ",i,r,r) // i = 0,1,2,4 , perfect!!
// as runes are made up of 4 bytes (rune is int32 and byte in unint8
// and a set of bytes is used to represent a rune which is used to
// represent UTF characters == the REAL CHARECTER
}
fmt.Println("\nValues in oneString ")
for j := 0; j < len(oneString); j++ {
fmt.Printf(" %d %v ",j,oneString[j]) // No you cannot get charecters if you iterate through string in this way
// as you are going over bytes here - not runes
}
fmt.Println("\nValues in twoByteArr")
for j := 0; j < len(twoByteArr); j++ {
fmt.Printf(" %d=%v ",j,twoByteArr[j]) // == same as above
}
fmt.Printf("\none - %s, two %s, three %s\n",oneString,twoByteArr,thrirdString)
}
And some more pointless demo https://play.golang.org/p/tagRBVG8k7V
adapted from https://groups.google.com/g/golang-nuts/c/84GCvDBhpbg/m/Tt6089MPFQAJ
to show that the 'characters' are encoded with one to up to 4 bytes depending on the unicode code point
Provide simple examples to understand how to do it quickly.
// rune => string
fmt.Printf("%c\n", 65) // A
fmt.Println(string(rune(0x1F60A))) // 😊
fmt.Println(string([]rune{0x1F468, 0x200D, 0x1F9B0})) // 👨‍🦰
// string => rune
fmt.Println(strconv.FormatUint(uint64([]rune("😊")[0]), 16)) // 1f60a
fmt.Printf("%U\n", '😊') // U+1F60A
fmt.Printf("%U %U %U\n", '👨', '‍', '🦰') // U+1F468 U+200D U+1F9B0
go playground

Golang Convert String to io.Writer?

Is it possible to convert a string to an io.Writer type in Golang?
I will be using this string in fmt.Fprintf() but I am unable to convert the type.
You can't write into a string, strings in Go are immutable.
The best alternatives are the bytes.Buffer and since Go 1.10 the faster strings.Builder types: they implement io.Writer so you can write into them, and you can obtain their content as a string with Buffer.String() and Builder.String(), or as a byte slice with Buffer.Bytes().
You can also have a string as the initial content of the buffer if you create the buffer with bytes.NewBufferString():
s := "Hello"
buf := bytes.NewBufferString(s)
fmt.Fprint(buf, ", World!")
fmt.Println(buf.String())
Output (try it on the Go Playground):
Hello, World!
If you want to append a variable of type string (or any value of string type), you can simply use Buffer.WriteString() (or Builder.WriteString()):
s2 := "to be appended"
buf.WriteString(s2)
Or:
fmt.Fprint(buf, s2)
Also note that if you just want to concatenate 2 strings, you don't need to create a buffer and use fmt.Fprintf(), you can simply use the + operator to concatenate them:
s := "Hello"
s2 := ", World!"
s3 := s + s2 // "Hello, World!"
Also see: Golang: format a string without printing?
It may also be of interest: What's the difference between ResponseWriter.Write and io.WriteString?
I saw the other answer mention strings.Builder, but I didn't see an example. So here you go:
package main
import (
"fmt"
"strings"
)
func main() {
b := new(strings.Builder)
fmt.Fprint(b, "south north")
println(b.String())
}
https://golang.org/pkg/strings#Builder
Use bytes.Buffer which implements the Write() method.
import "bytes"
writer := bytes.NewBufferString("your string")

Resources