Convert byte array to string

Wrote a simple program for codingame.com. It works.
Tried to change the output to print a string instead of individual bytes. The compiler doesn’t like it.
Compiler error message:

``````./Answer.go:80: cannot convert outes[i] (type [4]byte) to type string
``````

Program:

``````// Mini Sudoku solver -  solves a 4×4 sudoku grid that has only one solution.
package main

import "fmt"

func onebit(v uint8) int {  // if only one bit is set, return its position
n := 1                  // otherwise return 0
for (v>0) {
v >>= 1
if (v & 1)==1 {
if v==1 {   return n
} else  {   return 0
}
}
n++
}
return 0
}

func main() {
var lines[4]    string
var block[4][4] byte
var outes[4][4] byte

for i:=range lines {            // Read input, prep worksheets
fmt.Scan(&lines[i])
for j:=range block[0] {
outes[i][j] = lines[i][j]
block[i][j] = 0x1e
}
}

flag := 1
for flag>0 {
flag = 0
for i:=range block {            // eliminate possibilites
for j:=range block[0] {
if outes[i][j] != '0' {
mask := uint8(^(1 << (outes[i][j] - '0')))
for k:=range block[0] {
block[i][k] &= mask         // by row
}
for k:=range block {
block[k][j] &= mask         // by column
}
startx := j & 2;
starty := i & 2
for k:=starty; k<starty+2; k++ {        // by subblock
for m:=startx; m<startx+2; m++ {
}
}
}
}
}

for i:=range block {            // scan for single possible value
for j:=range block[0] {
if outes[i][j] == '0' {
n := onebit(block[i][j])
if n>0 {
outes[i][j] = byte(n + '0')    // add to solution
} else {
flag = 1
}
}
}
}
}

/*
for i:=range outes {
for j:=range outes[0] {
fmt.Printf("%c", outes[i][j])
}
fmt.Println()
}
*/
for i:=range outes {
fmt.Printf("%s\n", string(outes[i]))
}
}``````
1 Like

It seems that you can only convert to string a slice of bytes or []byte, in other words [4]byte (array) is not the same type of []byte (slice), so a possible solution may be create your var outes as an array of slices, something like:

``````var outes [4][]byte
``````

Slice the array, then convert it to string: Go Playground - The Go Programming Language

1 Like

Slice the array?!?! Yeah, okay, fine, Go likes slices. How do you perform this mystical operation? It’s easy, if you know the magic word. Line that failed:

``````fmt.Printf("%s\n", string(outes[i]))
``````

Line that works:

``````fmt.Printf("%s\n", string(outes[i][:]))
``````

Or, to simplify:

``fmt.Println(string(outes[i][:]))``

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.