How to assign string to bytes array
I want to assign string to bytes array:
var arr [20]byte
str := "abc"
for k, v := range byte(str)
arr[k] = byte(v)
Have another method?
go
add a comment |
I want to assign string to bytes array:
var arr [20]byte
str := "abc"
for k, v := range byte(str)
arr[k] = byte(v)
Have another method?
go
7
If the length ofstris greater than the length ofarrthen you will get an "index out of range" error.
– peterSO
Nov 7 '11 at 4:13
add a comment |
I want to assign string to bytes array:
var arr [20]byte
str := "abc"
for k, v := range byte(str)
arr[k] = byte(v)
Have another method?
go
I want to assign string to bytes array:
var arr [20]byte
str := "abc"
for k, v := range byte(str)
arr[k] = byte(v)
Have another method?
go
go
asked Nov 7 '11 at 2:29
sofiresofire
1,4312103
1,4312103
7
If the length ofstris greater than the length ofarrthen you will get an "index out of range" error.
– peterSO
Nov 7 '11 at 4:13
add a comment |
7
If the length ofstris greater than the length ofarrthen you will get an "index out of range" error.
– peterSO
Nov 7 '11 at 4:13
7
7
If the length of
str is greater than the length of arr then you will get an "index out of range" error.– peterSO
Nov 7 '11 at 4:13
If the length of
str is greater than the length of arr then you will get an "index out of range" error.– peterSO
Nov 7 '11 at 4:13
add a comment |
9 Answers
9
active
oldest
votes
Safe and simple:
byte("Here is a string....")
5
This answer is wrong:cannot use (byte)("abc") (type byte) as type [20]byte in field value
– DavidG
Feb 13 '16 at 6:51
12
Best coding practices in Go is using a slice of bytesbyteand not a set array of bytes[20]bytewhen converting a string to bytes... Don't believe me? Check out Rob Pike's answer on this thread
– openwonk
Feb 14 '16 at 0:44
6
The OP asked about an array, not a slice. In some cases you need to limit the size of the slice and use an array instead. My answer below trims the extra chars to make sure you do not overflow the array.
– DavidG
Feb 14 '16 at 5:17
4
Not what the OP was looking for, but was exactly what I needed! Thanks!
– Floating Sunfish
May 20 '17 at 3:55
2
For those who think this looks a little bit strange: this is just type conversion in Go: golang.org/ref/spec#Conversions
– Cnly
Feb 17 '18 at 14:08
|
show 1 more comment
For example,
package main
import "fmt"
func main()
s := "abc"
var a [20]byte
copy(a[:], s)
fmt.Println("s:", byte(s), "a:", a)
Output:
s: [97 98 99] a: [97 98 99 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
3
This is the only answer that actually addresses the original question.
– Jack O'Connor
Aug 19 '16 at 14:43
Why assign 20 bytes rather than specific about you actually need for the string ? If the string needs less than 20 isn't that bit inefficient? And also error prone if it exceeds 20 ?
– Sir
Nov 19 '17 at 22:03
1
@Sir: We don't assign 20 bytes. We copy 3 bytes, the length ofs, The `copy function is not dumb. Appending to and copying slices: "The number of elements copied is the minimum of len(src) and len(dst)."
– peterSO
Nov 19 '17 at 22:51
add a comment |
For converting from a string to a byte slice, string -> byte:
byte(str)
For converting an array to a slice, [20]byte -> byte:
arr[:]
For copying a string to an array, string -> [20]byte:
copy(arr[:], str)
Same as above, but explicitly converting the string to a slice first:
copy(arr[:], byte(str))
- The built-in
copyfunction only copies to a slice, from a slice. - Arrays are "the underlying data", while slices are "a viewport into underlying data".
- Using
[:]makes an array qualify as a slice. - A string qualifies as a slice.
- If the string is too long,
copywill only copy the part of the string that fits.
This code:
var arr [20]byte
copy(arr[:], "abc")
fmt.Printf("array: %v (%T)n", arr, arr)
...gives the following output:
array: [97 98 99 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] ([20]uint8)
I also made it available at the Go Playground
add a comment |
Piece of cake:
arr := byte("That's all folks!!")
6
This doesn't seem to be answering the question. OP wanted to write the string's bytes to an existing array that might be longer than the string.
– Jack O'Connor
Aug 19 '16 at 14:35
1
Using slicesbyteis preferred over arrays[20]byte. Answer is correct based on best practices; if specifications or code necessitates arrays, then usecopyinstead (see examples elsewhere in this thread).
– openwonk
Apr 6 '17 at 21:18
add a comment |
I think it's better..
package main
import "fmt"
func main()
str := "abc"
mySlice := byte(str)
fmt.Printf("%v -> '%s'",mySlice,mySlice )
Check here: http://play.golang.org/p/vpnAWHZZk7
3
It's not better. It's wrong. It doesn't do what the the question asked for.
– peterSO
Jul 12 '13 at 2:14
yeah @peterSO, you're right.
– chespinoza
Jul 12 '13 at 3:15
add a comment |
Go, convert a string to a bytes slice
You need a fast way to convert a string to byte type. To use in situations such as storing text data into a random access file or other type of data manipulation that requires the input data to be in byte type.
package main
func main()
var s string
//...
b := byte(s)
//...
which is useful when using ioutil.WriteFile, which accepts a bytes slice as its data parameter:
WriteFile func(filename string, data byte, perm os.FileMode) error
Another example
package main
import (
"fmt"
"strings"
)
func main()
stringSlice := string"hello", "world"
stringByte := strings.Join(stringSlice, " ")
// Byte array value
fmt.Println(byte(stringByte))
// Corresponding string value
fmt.Println(string(byte(stringByte)))
Output:
[104 101 108 108 111 32 119 111 114 108 100] hello world
Please check the link playground
add a comment |
Besides the methods mentioned above, you can also do a trick as
s := "hello"
b := *(*byte)(unsafe.Pointer((*reflect.SliceHeader)(unsafe.Pointer(&s))))
Go Play: http://play.golang.org/p/xASsiSpQmC
You should never use this :-)
1
This is crazy. I think it's worth adding "but you should not" at the end of your response. Apart from the fact it doesn't really answer the question (OP talks about bytes array, not slices), you don't seem to get a properbyteobject using your "conversion" – it fails badly when you try to amendp, see: play.golang.org/p/WHGl756ucj. In your case, not sure why you would prefer double-unsafe over theb := byte(s)method.
– tomasz
Jul 20 '15 at 11:57
1
@tomasz I'm not prefer to do string <-> byte in this way, just showing a different option :-) and yes you are right, I misunderstood the question.
– Brandon Gao
Jul 20 '15 at 16:05
When I do this, the result has acap()of arbitrary size, which means it's reading into unknown memory. For this to be right, I think you'd need to make sure you allocate the fullreflect.SliceHeadersize and manually set thecap. Something like this: play.golang.org/p/fBK4dZM-qD
– Lye Fish
Dec 31 '16 at 2:50
And I'm not even certain of that.-------------^-- Maybe this is better: play.golang.org/p/NJUxb20FTG
– Lye Fish
Dec 31 '16 at 3:04
add a comment |
Ended up creating array specific methods to do this. Much like the encoding/binary package with specific methods for each int type. For example binary.BigEndian.PutUint16(byte, uint16).
func byte16PutString(s string) [16]byte
var a [16]byte
if len(s) > 16
copy(a[:], s)
else
copy(a[16-len(s):], s)
return a
var b [16]byte
b = byte16PutString("abc")
fmt.Printf("%vn", b)
Output:
[0 0 0 0 0 0 0 0 0 0 0 0 0 97 98 99]
Notice how I wanted padding on the left, not the right.
http://play.golang.org/p/7tNumnJaiN
3
If you are down voting the answer please leave a comment on why you find the solution not optimal or how it isn't relevant to the OP's question.
– DavidG
May 18 '16 at 20:12
3
I think the downvotes are becausebyte16PutStringis a sort-of reimplementation of the builtincopyfunction, that only supports creating new arrays instead of using an existing one.copyhas special compiler support, so it can handle different types of arguments, and it probably has a really high-performance implementation under the covers. Also, the OP's question asked about writing a string to an existing array, rather than allocating a new one, though most of the other answers seem to be ignoring that too...
– Jack O'Connor
Aug 19 '16 at 14:41
Thanks @JackO'Connor I am in here for the learning too and appreciate the constructive feedback, not just the plain downvote.
– DavidG
Aug 29 '16 at 15:35
don't know y its down votedansweris correct every body is here to learn and encourage others
– muthukumar
Jun 13 '18 at 17:54
add a comment |
Arrays are values... slices are more like pointers. That is [n]type is not compatible with type as they are fundamentally two different things. You can get a slice that points to an array by using arr[:] which returns a slice that has arr as it's backing storage.
One way to convert a slice of for example byte to [20]byte is to actually allocate a [20]byte which you can do by using var [20]byte (as it's a value... no make needed) and then copy data into it:
buf := make(byte, 10)
var arr [10]byte
copy(arr[:], buf)
Essentially what a lot of other answers get wrong is that type is NOT an array.
[n]T and T are completely different things!
When using reflect T is not of kind Array but of kind Slice and [n]T is of kind Array.
You also can't use map[byte]T but you can use map[[n]byte]T.
This can sometimes be cumbersome because a lot of functions operate for example on byte whereas some functions return [n]byte (most notably the hash functions in crypto/*).
A sha256 hash for example is [32]byte and not byte so when beginners try to write it to a file for example:
sum := sha256.Sum256(data)
w.Write(sum)
they will get an error. The correct way of is to use
w.Write(sum[:])
However, what is it that you want? Just accessing the string bytewise? You can easily convert a string to byte using:
bytes := byte(str)
but this isn't an array, it's a slice. Also, byte != rune. In case you want to operate on "characters" you need to use rune... not byte.
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f8032170%2fhow-to-assign-string-to-bytes-array%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
9 Answers
9
active
oldest
votes
9 Answers
9
active
oldest
votes
active
oldest
votes
active
oldest
votes
Safe and simple:
byte("Here is a string....")
5
This answer is wrong:cannot use (byte)("abc") (type byte) as type [20]byte in field value
– DavidG
Feb 13 '16 at 6:51
12
Best coding practices in Go is using a slice of bytesbyteand not a set array of bytes[20]bytewhen converting a string to bytes... Don't believe me? Check out Rob Pike's answer on this thread
– openwonk
Feb 14 '16 at 0:44
6
The OP asked about an array, not a slice. In some cases you need to limit the size of the slice and use an array instead. My answer below trims the extra chars to make sure you do not overflow the array.
– DavidG
Feb 14 '16 at 5:17
4
Not what the OP was looking for, but was exactly what I needed! Thanks!
– Floating Sunfish
May 20 '17 at 3:55
2
For those who think this looks a little bit strange: this is just type conversion in Go: golang.org/ref/spec#Conversions
– Cnly
Feb 17 '18 at 14:08
|
show 1 more comment
Safe and simple:
byte("Here is a string....")
5
This answer is wrong:cannot use (byte)("abc") (type byte) as type [20]byte in field value
– DavidG
Feb 13 '16 at 6:51
12
Best coding practices in Go is using a slice of bytesbyteand not a set array of bytes[20]bytewhen converting a string to bytes... Don't believe me? Check out Rob Pike's answer on this thread
– openwonk
Feb 14 '16 at 0:44
6
The OP asked about an array, not a slice. In some cases you need to limit the size of the slice and use an array instead. My answer below trims the extra chars to make sure you do not overflow the array.
– DavidG
Feb 14 '16 at 5:17
4
Not what the OP was looking for, but was exactly what I needed! Thanks!
– Floating Sunfish
May 20 '17 at 3:55
2
For those who think this looks a little bit strange: this is just type conversion in Go: golang.org/ref/spec#Conversions
– Cnly
Feb 17 '18 at 14:08
|
show 1 more comment
Safe and simple:
byte("Here is a string....")
Safe and simple:
byte("Here is a string....")
answered Feb 1 '15 at 8:49
openwonkopenwonk
6,59221618
6,59221618
5
This answer is wrong:cannot use (byte)("abc") (type byte) as type [20]byte in field value
– DavidG
Feb 13 '16 at 6:51
12
Best coding practices in Go is using a slice of bytesbyteand not a set array of bytes[20]bytewhen converting a string to bytes... Don't believe me? Check out Rob Pike's answer on this thread
– openwonk
Feb 14 '16 at 0:44
6
The OP asked about an array, not a slice. In some cases you need to limit the size of the slice and use an array instead. My answer below trims the extra chars to make sure you do not overflow the array.
– DavidG
Feb 14 '16 at 5:17
4
Not what the OP was looking for, but was exactly what I needed! Thanks!
– Floating Sunfish
May 20 '17 at 3:55
2
For those who think this looks a little bit strange: this is just type conversion in Go: golang.org/ref/spec#Conversions
– Cnly
Feb 17 '18 at 14:08
|
show 1 more comment
5
This answer is wrong:cannot use (byte)("abc") (type byte) as type [20]byte in field value
– DavidG
Feb 13 '16 at 6:51
12
Best coding practices in Go is using a slice of bytesbyteand not a set array of bytes[20]bytewhen converting a string to bytes... Don't believe me? Check out Rob Pike's answer on this thread
– openwonk
Feb 14 '16 at 0:44
6
The OP asked about an array, not a slice. In some cases you need to limit the size of the slice and use an array instead. My answer below trims the extra chars to make sure you do not overflow the array.
– DavidG
Feb 14 '16 at 5:17
4
Not what the OP was looking for, but was exactly what I needed! Thanks!
– Floating Sunfish
May 20 '17 at 3:55
2
For those who think this looks a little bit strange: this is just type conversion in Go: golang.org/ref/spec#Conversions
– Cnly
Feb 17 '18 at 14:08
5
5
This answer is wrong:
cannot use (byte)("abc") (type byte) as type [20]byte in field value– DavidG
Feb 13 '16 at 6:51
This answer is wrong:
cannot use (byte)("abc") (type byte) as type [20]byte in field value– DavidG
Feb 13 '16 at 6:51
12
12
Best coding practices in Go is using a slice of bytes
byte and not a set array of bytes [20]byte when converting a string to bytes... Don't believe me? Check out Rob Pike's answer on this thread– openwonk
Feb 14 '16 at 0:44
Best coding practices in Go is using a slice of bytes
byte and not a set array of bytes [20]byte when converting a string to bytes... Don't believe me? Check out Rob Pike's answer on this thread– openwonk
Feb 14 '16 at 0:44
6
6
The OP asked about an array, not a slice. In some cases you need to limit the size of the slice and use an array instead. My answer below trims the extra chars to make sure you do not overflow the array.
– DavidG
Feb 14 '16 at 5:17
The OP asked about an array, not a slice. In some cases you need to limit the size of the slice and use an array instead. My answer below trims the extra chars to make sure you do not overflow the array.
– DavidG
Feb 14 '16 at 5:17
4
4
Not what the OP was looking for, but was exactly what I needed! Thanks!
– Floating Sunfish
May 20 '17 at 3:55
Not what the OP was looking for, but was exactly what I needed! Thanks!
– Floating Sunfish
May 20 '17 at 3:55
2
2
For those who think this looks a little bit strange: this is just type conversion in Go: golang.org/ref/spec#Conversions
– Cnly
Feb 17 '18 at 14:08
For those who think this looks a little bit strange: this is just type conversion in Go: golang.org/ref/spec#Conversions
– Cnly
Feb 17 '18 at 14:08
|
show 1 more comment
For example,
package main
import "fmt"
func main()
s := "abc"
var a [20]byte
copy(a[:], s)
fmt.Println("s:", byte(s), "a:", a)
Output:
s: [97 98 99] a: [97 98 99 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
3
This is the only answer that actually addresses the original question.
– Jack O'Connor
Aug 19 '16 at 14:43
Why assign 20 bytes rather than specific about you actually need for the string ? If the string needs less than 20 isn't that bit inefficient? And also error prone if it exceeds 20 ?
– Sir
Nov 19 '17 at 22:03
1
@Sir: We don't assign 20 bytes. We copy 3 bytes, the length ofs, The `copy function is not dumb. Appending to and copying slices: "The number of elements copied is the minimum of len(src) and len(dst)."
– peterSO
Nov 19 '17 at 22:51
add a comment |
For example,
package main
import "fmt"
func main()
s := "abc"
var a [20]byte
copy(a[:], s)
fmt.Println("s:", byte(s), "a:", a)
Output:
s: [97 98 99] a: [97 98 99 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
3
This is the only answer that actually addresses the original question.
– Jack O'Connor
Aug 19 '16 at 14:43
Why assign 20 bytes rather than specific about you actually need for the string ? If the string needs less than 20 isn't that bit inefficient? And also error prone if it exceeds 20 ?
– Sir
Nov 19 '17 at 22:03
1
@Sir: We don't assign 20 bytes. We copy 3 bytes, the length ofs, The `copy function is not dumb. Appending to and copying slices: "The number of elements copied is the minimum of len(src) and len(dst)."
– peterSO
Nov 19 '17 at 22:51
add a comment |
For example,
package main
import "fmt"
func main()
s := "abc"
var a [20]byte
copy(a[:], s)
fmt.Println("s:", byte(s), "a:", a)
Output:
s: [97 98 99] a: [97 98 99 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
For example,
package main
import "fmt"
func main()
s := "abc"
var a [20]byte
copy(a[:], s)
fmt.Println("s:", byte(s), "a:", a)
Output:
s: [97 98 99] a: [97 98 99 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
edited Nov 7 '11 at 4:07
answered Nov 7 '11 at 3:55
peterSOpeterSO
95.2k14160175
95.2k14160175
3
This is the only answer that actually addresses the original question.
– Jack O'Connor
Aug 19 '16 at 14:43
Why assign 20 bytes rather than specific about you actually need for the string ? If the string needs less than 20 isn't that bit inefficient? And also error prone if it exceeds 20 ?
– Sir
Nov 19 '17 at 22:03
1
@Sir: We don't assign 20 bytes. We copy 3 bytes, the length ofs, The `copy function is not dumb. Appending to and copying slices: "The number of elements copied is the minimum of len(src) and len(dst)."
– peterSO
Nov 19 '17 at 22:51
add a comment |
3
This is the only answer that actually addresses the original question.
– Jack O'Connor
Aug 19 '16 at 14:43
Why assign 20 bytes rather than specific about you actually need for the string ? If the string needs less than 20 isn't that bit inefficient? And also error prone if it exceeds 20 ?
– Sir
Nov 19 '17 at 22:03
1
@Sir: We don't assign 20 bytes. We copy 3 bytes, the length ofs, The `copy function is not dumb. Appending to and copying slices: "The number of elements copied is the minimum of len(src) and len(dst)."
– peterSO
Nov 19 '17 at 22:51
3
3
This is the only answer that actually addresses the original question.
– Jack O'Connor
Aug 19 '16 at 14:43
This is the only answer that actually addresses the original question.
– Jack O'Connor
Aug 19 '16 at 14:43
Why assign 20 bytes rather than specific about you actually need for the string ? If the string needs less than 20 isn't that bit inefficient? And also error prone if it exceeds 20 ?
– Sir
Nov 19 '17 at 22:03
Why assign 20 bytes rather than specific about you actually need for the string ? If the string needs less than 20 isn't that bit inefficient? And also error prone if it exceeds 20 ?
– Sir
Nov 19 '17 at 22:03
1
1
@Sir: We don't assign 20 bytes. We copy 3 bytes, the length of
s, The `copy function is not dumb. Appending to and copying slices: "The number of elements copied is the minimum of len(src) and len(dst)."– peterSO
Nov 19 '17 at 22:51
@Sir: We don't assign 20 bytes. We copy 3 bytes, the length of
s, The `copy function is not dumb. Appending to and copying slices: "The number of elements copied is the minimum of len(src) and len(dst)."– peterSO
Nov 19 '17 at 22:51
add a comment |
For converting from a string to a byte slice, string -> byte:
byte(str)
For converting an array to a slice, [20]byte -> byte:
arr[:]
For copying a string to an array, string -> [20]byte:
copy(arr[:], str)
Same as above, but explicitly converting the string to a slice first:
copy(arr[:], byte(str))
- The built-in
copyfunction only copies to a slice, from a slice. - Arrays are "the underlying data", while slices are "a viewport into underlying data".
- Using
[:]makes an array qualify as a slice. - A string qualifies as a slice.
- If the string is too long,
copywill only copy the part of the string that fits.
This code:
var arr [20]byte
copy(arr[:], "abc")
fmt.Printf("array: %v (%T)n", arr, arr)
...gives the following output:
array: [97 98 99 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] ([20]uint8)
I also made it available at the Go Playground
add a comment |
For converting from a string to a byte slice, string -> byte:
byte(str)
For converting an array to a slice, [20]byte -> byte:
arr[:]
For copying a string to an array, string -> [20]byte:
copy(arr[:], str)
Same as above, but explicitly converting the string to a slice first:
copy(arr[:], byte(str))
- The built-in
copyfunction only copies to a slice, from a slice. - Arrays are "the underlying data", while slices are "a viewport into underlying data".
- Using
[:]makes an array qualify as a slice. - A string qualifies as a slice.
- If the string is too long,
copywill only copy the part of the string that fits.
This code:
var arr [20]byte
copy(arr[:], "abc")
fmt.Printf("array: %v (%T)n", arr, arr)
...gives the following output:
array: [97 98 99 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] ([20]uint8)
I also made it available at the Go Playground
add a comment |
For converting from a string to a byte slice, string -> byte:
byte(str)
For converting an array to a slice, [20]byte -> byte:
arr[:]
For copying a string to an array, string -> [20]byte:
copy(arr[:], str)
Same as above, but explicitly converting the string to a slice first:
copy(arr[:], byte(str))
- The built-in
copyfunction only copies to a slice, from a slice. - Arrays are "the underlying data", while slices are "a viewport into underlying data".
- Using
[:]makes an array qualify as a slice. - A string qualifies as a slice.
- If the string is too long,
copywill only copy the part of the string that fits.
This code:
var arr [20]byte
copy(arr[:], "abc")
fmt.Printf("array: %v (%T)n", arr, arr)
...gives the following output:
array: [97 98 99 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] ([20]uint8)
I also made it available at the Go Playground
For converting from a string to a byte slice, string -> byte:
byte(str)
For converting an array to a slice, [20]byte -> byte:
arr[:]
For copying a string to an array, string -> [20]byte:
copy(arr[:], str)
Same as above, but explicitly converting the string to a slice first:
copy(arr[:], byte(str))
- The built-in
copyfunction only copies to a slice, from a slice. - Arrays are "the underlying data", while slices are "a viewport into underlying data".
- Using
[:]makes an array qualify as a slice. - A string qualifies as a slice.
- If the string is too long,
copywill only copy the part of the string that fits.
This code:
var arr [20]byte
copy(arr[:], "abc")
fmt.Printf("array: %v (%T)n", arr, arr)
...gives the following output:
array: [97 98 99 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] ([20]uint8)
I also made it available at the Go Playground
edited Nov 26 '18 at 8:52
answered Sep 2 '16 at 14:20
AlexanderAlexander
5,29623645
5,29623645
add a comment |
add a comment |
Piece of cake:
arr := byte("That's all folks!!")
6
This doesn't seem to be answering the question. OP wanted to write the string's bytes to an existing array that might be longer than the string.
– Jack O'Connor
Aug 19 '16 at 14:35
1
Using slicesbyteis preferred over arrays[20]byte. Answer is correct based on best practices; if specifications or code necessitates arrays, then usecopyinstead (see examples elsewhere in this thread).
– openwonk
Apr 6 '17 at 21:18
add a comment |
Piece of cake:
arr := byte("That's all folks!!")
6
This doesn't seem to be answering the question. OP wanted to write the string's bytes to an existing array that might be longer than the string.
– Jack O'Connor
Aug 19 '16 at 14:35
1
Using slicesbyteis preferred over arrays[20]byte. Answer is correct based on best practices; if specifications or code necessitates arrays, then usecopyinstead (see examples elsewhere in this thread).
– openwonk
Apr 6 '17 at 21:18
add a comment |
Piece of cake:
arr := byte("That's all folks!!")
Piece of cake:
arr := byte("That's all folks!!")
answered Jan 26 '16 at 10:58
Sameh SharafSameh Sharaf
673613
673613
6
This doesn't seem to be answering the question. OP wanted to write the string's bytes to an existing array that might be longer than the string.
– Jack O'Connor
Aug 19 '16 at 14:35
1
Using slicesbyteis preferred over arrays[20]byte. Answer is correct based on best practices; if specifications or code necessitates arrays, then usecopyinstead (see examples elsewhere in this thread).
– openwonk
Apr 6 '17 at 21:18
add a comment |
6
This doesn't seem to be answering the question. OP wanted to write the string's bytes to an existing array that might be longer than the string.
– Jack O'Connor
Aug 19 '16 at 14:35
1
Using slicesbyteis preferred over arrays[20]byte. Answer is correct based on best practices; if specifications or code necessitates arrays, then usecopyinstead (see examples elsewhere in this thread).
– openwonk
Apr 6 '17 at 21:18
6
6
This doesn't seem to be answering the question. OP wanted to write the string's bytes to an existing array that might be longer than the string.
– Jack O'Connor
Aug 19 '16 at 14:35
This doesn't seem to be answering the question. OP wanted to write the string's bytes to an existing array that might be longer than the string.
– Jack O'Connor
Aug 19 '16 at 14:35
1
1
Using slices
byte is preferred over arrays [20]byte. Answer is correct based on best practices; if specifications or code necessitates arrays, then use copy instead (see examples elsewhere in this thread).– openwonk
Apr 6 '17 at 21:18
Using slices
byte is preferred over arrays [20]byte. Answer is correct based on best practices; if specifications or code necessitates arrays, then use copy instead (see examples elsewhere in this thread).– openwonk
Apr 6 '17 at 21:18
add a comment |
I think it's better..
package main
import "fmt"
func main()
str := "abc"
mySlice := byte(str)
fmt.Printf("%v -> '%s'",mySlice,mySlice )
Check here: http://play.golang.org/p/vpnAWHZZk7
3
It's not better. It's wrong. It doesn't do what the the question asked for.
– peterSO
Jul 12 '13 at 2:14
yeah @peterSO, you're right.
– chespinoza
Jul 12 '13 at 3:15
add a comment |
I think it's better..
package main
import "fmt"
func main()
str := "abc"
mySlice := byte(str)
fmt.Printf("%v -> '%s'",mySlice,mySlice )
Check here: http://play.golang.org/p/vpnAWHZZk7
3
It's not better. It's wrong. It doesn't do what the the question asked for.
– peterSO
Jul 12 '13 at 2:14
yeah @peterSO, you're right.
– chespinoza
Jul 12 '13 at 3:15
add a comment |
I think it's better..
package main
import "fmt"
func main()
str := "abc"
mySlice := byte(str)
fmt.Printf("%v -> '%s'",mySlice,mySlice )
Check here: http://play.golang.org/p/vpnAWHZZk7
I think it's better..
package main
import "fmt"
func main()
str := "abc"
mySlice := byte(str)
fmt.Printf("%v -> '%s'",mySlice,mySlice )
Check here: http://play.golang.org/p/vpnAWHZZk7
answered Jul 11 '13 at 23:08
chespinozachespinoza
1,9441738
1,9441738
3
It's not better. It's wrong. It doesn't do what the the question asked for.
– peterSO
Jul 12 '13 at 2:14
yeah @peterSO, you're right.
– chespinoza
Jul 12 '13 at 3:15
add a comment |
3
It's not better. It's wrong. It doesn't do what the the question asked for.
– peterSO
Jul 12 '13 at 2:14
yeah @peterSO, you're right.
– chespinoza
Jul 12 '13 at 3:15
3
3
It's not better. It's wrong. It doesn't do what the the question asked for.
– peterSO
Jul 12 '13 at 2:14
It's not better. It's wrong. It doesn't do what the the question asked for.
– peterSO
Jul 12 '13 at 2:14
yeah @peterSO, you're right.
– chespinoza
Jul 12 '13 at 3:15
yeah @peterSO, you're right.
– chespinoza
Jul 12 '13 at 3:15
add a comment |
Go, convert a string to a bytes slice
You need a fast way to convert a string to byte type. To use in situations such as storing text data into a random access file or other type of data manipulation that requires the input data to be in byte type.
package main
func main()
var s string
//...
b := byte(s)
//...
which is useful when using ioutil.WriteFile, which accepts a bytes slice as its data parameter:
WriteFile func(filename string, data byte, perm os.FileMode) error
Another example
package main
import (
"fmt"
"strings"
)
func main()
stringSlice := string"hello", "world"
stringByte := strings.Join(stringSlice, " ")
// Byte array value
fmt.Println(byte(stringByte))
// Corresponding string value
fmt.Println(string(byte(stringByte)))
Output:
[104 101 108 108 111 32 119 111 114 108 100] hello world
Please check the link playground
add a comment |
Go, convert a string to a bytes slice
You need a fast way to convert a string to byte type. To use in situations such as storing text data into a random access file or other type of data manipulation that requires the input data to be in byte type.
package main
func main()
var s string
//...
b := byte(s)
//...
which is useful when using ioutil.WriteFile, which accepts a bytes slice as its data parameter:
WriteFile func(filename string, data byte, perm os.FileMode) error
Another example
package main
import (
"fmt"
"strings"
)
func main()
stringSlice := string"hello", "world"
stringByte := strings.Join(stringSlice, " ")
// Byte array value
fmt.Println(byte(stringByte))
// Corresponding string value
fmt.Println(string(byte(stringByte)))
Output:
[104 101 108 108 111 32 119 111 114 108 100] hello world
Please check the link playground
add a comment |
Go, convert a string to a bytes slice
You need a fast way to convert a string to byte type. To use in situations such as storing text data into a random access file or other type of data manipulation that requires the input data to be in byte type.
package main
func main()
var s string
//...
b := byte(s)
//...
which is useful when using ioutil.WriteFile, which accepts a bytes slice as its data parameter:
WriteFile func(filename string, data byte, perm os.FileMode) error
Another example
package main
import (
"fmt"
"strings"
)
func main()
stringSlice := string"hello", "world"
stringByte := strings.Join(stringSlice, " ")
// Byte array value
fmt.Println(byte(stringByte))
// Corresponding string value
fmt.Println(string(byte(stringByte)))
Output:
[104 101 108 108 111 32 119 111 114 108 100] hello world
Please check the link playground
Go, convert a string to a bytes slice
You need a fast way to convert a string to byte type. To use in situations such as storing text data into a random access file or other type of data manipulation that requires the input data to be in byte type.
package main
func main()
var s string
//...
b := byte(s)
//...
which is useful when using ioutil.WriteFile, which accepts a bytes slice as its data parameter:
WriteFile func(filename string, data byte, perm os.FileMode) error
Another example
package main
import (
"fmt"
"strings"
)
func main()
stringSlice := string"hello", "world"
stringByte := strings.Join(stringSlice, " ")
// Byte array value
fmt.Println(byte(stringByte))
// Corresponding string value
fmt.Println(string(byte(stringByte)))
Output:
[104 101 108 108 111 32 119 111 114 108 100] hello world
Please check the link playground
answered Nov 5 '18 at 9:28
ASHWIN RAJEEVASHWIN RAJEEV
201211
201211
add a comment |
add a comment |
Besides the methods mentioned above, you can also do a trick as
s := "hello"
b := *(*byte)(unsafe.Pointer((*reflect.SliceHeader)(unsafe.Pointer(&s))))
Go Play: http://play.golang.org/p/xASsiSpQmC
You should never use this :-)
1
This is crazy. I think it's worth adding "but you should not" at the end of your response. Apart from the fact it doesn't really answer the question (OP talks about bytes array, not slices), you don't seem to get a properbyteobject using your "conversion" – it fails badly when you try to amendp, see: play.golang.org/p/WHGl756ucj. In your case, not sure why you would prefer double-unsafe over theb := byte(s)method.
– tomasz
Jul 20 '15 at 11:57
1
@tomasz I'm not prefer to do string <-> byte in this way, just showing a different option :-) and yes you are right, I misunderstood the question.
– Brandon Gao
Jul 20 '15 at 16:05
When I do this, the result has acap()of arbitrary size, which means it's reading into unknown memory. For this to be right, I think you'd need to make sure you allocate the fullreflect.SliceHeadersize and manually set thecap. Something like this: play.golang.org/p/fBK4dZM-qD
– Lye Fish
Dec 31 '16 at 2:50
And I'm not even certain of that.-------------^-- Maybe this is better: play.golang.org/p/NJUxb20FTG
– Lye Fish
Dec 31 '16 at 3:04
add a comment |
Besides the methods mentioned above, you can also do a trick as
s := "hello"
b := *(*byte)(unsafe.Pointer((*reflect.SliceHeader)(unsafe.Pointer(&s))))
Go Play: http://play.golang.org/p/xASsiSpQmC
You should never use this :-)
1
This is crazy. I think it's worth adding "but you should not" at the end of your response. Apart from the fact it doesn't really answer the question (OP talks about bytes array, not slices), you don't seem to get a properbyteobject using your "conversion" – it fails badly when you try to amendp, see: play.golang.org/p/WHGl756ucj. In your case, not sure why you would prefer double-unsafe over theb := byte(s)method.
– tomasz
Jul 20 '15 at 11:57
1
@tomasz I'm not prefer to do string <-> byte in this way, just showing a different option :-) and yes you are right, I misunderstood the question.
– Brandon Gao
Jul 20 '15 at 16:05
When I do this, the result has acap()of arbitrary size, which means it's reading into unknown memory. For this to be right, I think you'd need to make sure you allocate the fullreflect.SliceHeadersize and manually set thecap. Something like this: play.golang.org/p/fBK4dZM-qD
– Lye Fish
Dec 31 '16 at 2:50
And I'm not even certain of that.-------------^-- Maybe this is better: play.golang.org/p/NJUxb20FTG
– Lye Fish
Dec 31 '16 at 3:04
add a comment |
Besides the methods mentioned above, you can also do a trick as
s := "hello"
b := *(*byte)(unsafe.Pointer((*reflect.SliceHeader)(unsafe.Pointer(&s))))
Go Play: http://play.golang.org/p/xASsiSpQmC
You should never use this :-)
Besides the methods mentioned above, you can also do a trick as
s := "hello"
b := *(*byte)(unsafe.Pointer((*reflect.SliceHeader)(unsafe.Pointer(&s))))
Go Play: http://play.golang.org/p/xASsiSpQmC
You should never use this :-)
edited Jul 20 '15 at 16:05
answered Jul 20 '15 at 9:56
Brandon GaoBrandon Gao
59049
59049
1
This is crazy. I think it's worth adding "but you should not" at the end of your response. Apart from the fact it doesn't really answer the question (OP talks about bytes array, not slices), you don't seem to get a properbyteobject using your "conversion" – it fails badly when you try to amendp, see: play.golang.org/p/WHGl756ucj. In your case, not sure why you would prefer double-unsafe over theb := byte(s)method.
– tomasz
Jul 20 '15 at 11:57
1
@tomasz I'm not prefer to do string <-> byte in this way, just showing a different option :-) and yes you are right, I misunderstood the question.
– Brandon Gao
Jul 20 '15 at 16:05
When I do this, the result has acap()of arbitrary size, which means it's reading into unknown memory. For this to be right, I think you'd need to make sure you allocate the fullreflect.SliceHeadersize and manually set thecap. Something like this: play.golang.org/p/fBK4dZM-qD
– Lye Fish
Dec 31 '16 at 2:50
And I'm not even certain of that.-------------^-- Maybe this is better: play.golang.org/p/NJUxb20FTG
– Lye Fish
Dec 31 '16 at 3:04
add a comment |
1
This is crazy. I think it's worth adding "but you should not" at the end of your response. Apart from the fact it doesn't really answer the question (OP talks about bytes array, not slices), you don't seem to get a properbyteobject using your "conversion" – it fails badly when you try to amendp, see: play.golang.org/p/WHGl756ucj. In your case, not sure why you would prefer double-unsafe over theb := byte(s)method.
– tomasz
Jul 20 '15 at 11:57
1
@tomasz I'm not prefer to do string <-> byte in this way, just showing a different option :-) and yes you are right, I misunderstood the question.
– Brandon Gao
Jul 20 '15 at 16:05
When I do this, the result has acap()of arbitrary size, which means it's reading into unknown memory. For this to be right, I think you'd need to make sure you allocate the fullreflect.SliceHeadersize and manually set thecap. Something like this: play.golang.org/p/fBK4dZM-qD
– Lye Fish
Dec 31 '16 at 2:50
And I'm not even certain of that.-------------^-- Maybe this is better: play.golang.org/p/NJUxb20FTG
– Lye Fish
Dec 31 '16 at 3:04
1
1
This is crazy. I think it's worth adding "but you should not" at the end of your response. Apart from the fact it doesn't really answer the question (OP talks about bytes array, not slices), you don't seem to get a proper
byte object using your "conversion" – it fails badly when you try to amend p, see: play.golang.org/p/WHGl756ucj. In your case, not sure why you would prefer double-unsafe over the b := byte(s) method.– tomasz
Jul 20 '15 at 11:57
This is crazy. I think it's worth adding "but you should not" at the end of your response. Apart from the fact it doesn't really answer the question (OP talks about bytes array, not slices), you don't seem to get a proper
byte object using your "conversion" – it fails badly when you try to amend p, see: play.golang.org/p/WHGl756ucj. In your case, not sure why you would prefer double-unsafe over the b := byte(s) method.– tomasz
Jul 20 '15 at 11:57
1
1
@tomasz I'm not prefer to do string <-> byte in this way, just showing a different option :-) and yes you are right, I misunderstood the question.
– Brandon Gao
Jul 20 '15 at 16:05
@tomasz I'm not prefer to do string <-> byte in this way, just showing a different option :-) and yes you are right, I misunderstood the question.
– Brandon Gao
Jul 20 '15 at 16:05
When I do this, the result has a
cap() of arbitrary size, which means it's reading into unknown memory. For this to be right, I think you'd need to make sure you allocate the full reflect.SliceHeader size and manually set the cap. Something like this: play.golang.org/p/fBK4dZM-qD– Lye Fish
Dec 31 '16 at 2:50
When I do this, the result has a
cap() of arbitrary size, which means it's reading into unknown memory. For this to be right, I think you'd need to make sure you allocate the full reflect.SliceHeader size and manually set the cap. Something like this: play.golang.org/p/fBK4dZM-qD– Lye Fish
Dec 31 '16 at 2:50
And I'm not even certain of that.-------------^-- Maybe this is better: play.golang.org/p/NJUxb20FTG
– Lye Fish
Dec 31 '16 at 3:04
And I'm not even certain of that.-------------^-- Maybe this is better: play.golang.org/p/NJUxb20FTG
– Lye Fish
Dec 31 '16 at 3:04
add a comment |
Ended up creating array specific methods to do this. Much like the encoding/binary package with specific methods for each int type. For example binary.BigEndian.PutUint16(byte, uint16).
func byte16PutString(s string) [16]byte
var a [16]byte
if len(s) > 16
copy(a[:], s)
else
copy(a[16-len(s):], s)
return a
var b [16]byte
b = byte16PutString("abc")
fmt.Printf("%vn", b)
Output:
[0 0 0 0 0 0 0 0 0 0 0 0 0 97 98 99]
Notice how I wanted padding on the left, not the right.
http://play.golang.org/p/7tNumnJaiN
3
If you are down voting the answer please leave a comment on why you find the solution not optimal or how it isn't relevant to the OP's question.
– DavidG
May 18 '16 at 20:12
3
I think the downvotes are becausebyte16PutStringis a sort-of reimplementation of the builtincopyfunction, that only supports creating new arrays instead of using an existing one.copyhas special compiler support, so it can handle different types of arguments, and it probably has a really high-performance implementation under the covers. Also, the OP's question asked about writing a string to an existing array, rather than allocating a new one, though most of the other answers seem to be ignoring that too...
– Jack O'Connor
Aug 19 '16 at 14:41
Thanks @JackO'Connor I am in here for the learning too and appreciate the constructive feedback, not just the plain downvote.
– DavidG
Aug 29 '16 at 15:35
don't know y its down votedansweris correct every body is here to learn and encourage others
– muthukumar
Jun 13 '18 at 17:54
add a comment |
Ended up creating array specific methods to do this. Much like the encoding/binary package with specific methods for each int type. For example binary.BigEndian.PutUint16(byte, uint16).
func byte16PutString(s string) [16]byte
var a [16]byte
if len(s) > 16
copy(a[:], s)
else
copy(a[16-len(s):], s)
return a
var b [16]byte
b = byte16PutString("abc")
fmt.Printf("%vn", b)
Output:
[0 0 0 0 0 0 0 0 0 0 0 0 0 97 98 99]
Notice how I wanted padding on the left, not the right.
http://play.golang.org/p/7tNumnJaiN
3
If you are down voting the answer please leave a comment on why you find the solution not optimal or how it isn't relevant to the OP's question.
– DavidG
May 18 '16 at 20:12
3
I think the downvotes are becausebyte16PutStringis a sort-of reimplementation of the builtincopyfunction, that only supports creating new arrays instead of using an existing one.copyhas special compiler support, so it can handle different types of arguments, and it probably has a really high-performance implementation under the covers. Also, the OP's question asked about writing a string to an existing array, rather than allocating a new one, though most of the other answers seem to be ignoring that too...
– Jack O'Connor
Aug 19 '16 at 14:41
Thanks @JackO'Connor I am in here for the learning too and appreciate the constructive feedback, not just the plain downvote.
– DavidG
Aug 29 '16 at 15:35
don't know y its down votedansweris correct every body is here to learn and encourage others
– muthukumar
Jun 13 '18 at 17:54
add a comment |
Ended up creating array specific methods to do this. Much like the encoding/binary package with specific methods for each int type. For example binary.BigEndian.PutUint16(byte, uint16).
func byte16PutString(s string) [16]byte
var a [16]byte
if len(s) > 16
copy(a[:], s)
else
copy(a[16-len(s):], s)
return a
var b [16]byte
b = byte16PutString("abc")
fmt.Printf("%vn", b)
Output:
[0 0 0 0 0 0 0 0 0 0 0 0 0 97 98 99]
Notice how I wanted padding on the left, not the right.
http://play.golang.org/p/7tNumnJaiN
Ended up creating array specific methods to do this. Much like the encoding/binary package with specific methods for each int type. For example binary.BigEndian.PutUint16(byte, uint16).
func byte16PutString(s string) [16]byte
var a [16]byte
if len(s) > 16
copy(a[:], s)
else
copy(a[16-len(s):], s)
return a
var b [16]byte
b = byte16PutString("abc")
fmt.Printf("%vn", b)
Output:
[0 0 0 0 0 0 0 0 0 0 0 0 0 97 98 99]
Notice how I wanted padding on the left, not the right.
http://play.golang.org/p/7tNumnJaiN
answered Feb 13 '16 at 7:13
DavidGDavidG
2,34922136
2,34922136
3
If you are down voting the answer please leave a comment on why you find the solution not optimal or how it isn't relevant to the OP's question.
– DavidG
May 18 '16 at 20:12
3
I think the downvotes are becausebyte16PutStringis a sort-of reimplementation of the builtincopyfunction, that only supports creating new arrays instead of using an existing one.copyhas special compiler support, so it can handle different types of arguments, and it probably has a really high-performance implementation under the covers. Also, the OP's question asked about writing a string to an existing array, rather than allocating a new one, though most of the other answers seem to be ignoring that too...
– Jack O'Connor
Aug 19 '16 at 14:41
Thanks @JackO'Connor I am in here for the learning too and appreciate the constructive feedback, not just the plain downvote.
– DavidG
Aug 29 '16 at 15:35
don't know y its down votedansweris correct every body is here to learn and encourage others
– muthukumar
Jun 13 '18 at 17:54
add a comment |
3
If you are down voting the answer please leave a comment on why you find the solution not optimal or how it isn't relevant to the OP's question.
– DavidG
May 18 '16 at 20:12
3
I think the downvotes are becausebyte16PutStringis a sort-of reimplementation of the builtincopyfunction, that only supports creating new arrays instead of using an existing one.copyhas special compiler support, so it can handle different types of arguments, and it probably has a really high-performance implementation under the covers. Also, the OP's question asked about writing a string to an existing array, rather than allocating a new one, though most of the other answers seem to be ignoring that too...
– Jack O'Connor
Aug 19 '16 at 14:41
Thanks @JackO'Connor I am in here for the learning too and appreciate the constructive feedback, not just the plain downvote.
– DavidG
Aug 29 '16 at 15:35
don't know y its down votedansweris correct every body is here to learn and encourage others
– muthukumar
Jun 13 '18 at 17:54
3
3
If you are down voting the answer please leave a comment on why you find the solution not optimal or how it isn't relevant to the OP's question.
– DavidG
May 18 '16 at 20:12
If you are down voting the answer please leave a comment on why you find the solution not optimal or how it isn't relevant to the OP's question.
– DavidG
May 18 '16 at 20:12
3
3
I think the downvotes are because
byte16PutString is a sort-of reimplementation of the builtin copy function, that only supports creating new arrays instead of using an existing one. copy has special compiler support, so it can handle different types of arguments, and it probably has a really high-performance implementation under the covers. Also, the OP's question asked about writing a string to an existing array, rather than allocating a new one, though most of the other answers seem to be ignoring that too...– Jack O'Connor
Aug 19 '16 at 14:41
I think the downvotes are because
byte16PutString is a sort-of reimplementation of the builtin copy function, that only supports creating new arrays instead of using an existing one. copy has special compiler support, so it can handle different types of arguments, and it probably has a really high-performance implementation under the covers. Also, the OP's question asked about writing a string to an existing array, rather than allocating a new one, though most of the other answers seem to be ignoring that too...– Jack O'Connor
Aug 19 '16 at 14:41
Thanks @JackO'Connor I am in here for the learning too and appreciate the constructive feedback, not just the plain downvote.
– DavidG
Aug 29 '16 at 15:35
Thanks @JackO'Connor I am in here for the learning too and appreciate the constructive feedback, not just the plain downvote.
– DavidG
Aug 29 '16 at 15:35
don't know y its down voted
answer is correct every body is here to learn and encourage others– muthukumar
Jun 13 '18 at 17:54
don't know y its down voted
answer is correct every body is here to learn and encourage others– muthukumar
Jun 13 '18 at 17:54
add a comment |
Arrays are values... slices are more like pointers. That is [n]type is not compatible with type as they are fundamentally two different things. You can get a slice that points to an array by using arr[:] which returns a slice that has arr as it's backing storage.
One way to convert a slice of for example byte to [20]byte is to actually allocate a [20]byte which you can do by using var [20]byte (as it's a value... no make needed) and then copy data into it:
buf := make(byte, 10)
var arr [10]byte
copy(arr[:], buf)
Essentially what a lot of other answers get wrong is that type is NOT an array.
[n]T and T are completely different things!
When using reflect T is not of kind Array but of kind Slice and [n]T is of kind Array.
You also can't use map[byte]T but you can use map[[n]byte]T.
This can sometimes be cumbersome because a lot of functions operate for example on byte whereas some functions return [n]byte (most notably the hash functions in crypto/*).
A sha256 hash for example is [32]byte and not byte so when beginners try to write it to a file for example:
sum := sha256.Sum256(data)
w.Write(sum)
they will get an error. The correct way of is to use
w.Write(sum[:])
However, what is it that you want? Just accessing the string bytewise? You can easily convert a string to byte using:
bytes := byte(str)
but this isn't an array, it's a slice. Also, byte != rune. In case you want to operate on "characters" you need to use rune... not byte.
add a comment |
Arrays are values... slices are more like pointers. That is [n]type is not compatible with type as they are fundamentally two different things. You can get a slice that points to an array by using arr[:] which returns a slice that has arr as it's backing storage.
One way to convert a slice of for example byte to [20]byte is to actually allocate a [20]byte which you can do by using var [20]byte (as it's a value... no make needed) and then copy data into it:
buf := make(byte, 10)
var arr [10]byte
copy(arr[:], buf)
Essentially what a lot of other answers get wrong is that type is NOT an array.
[n]T and T are completely different things!
When using reflect T is not of kind Array but of kind Slice and [n]T is of kind Array.
You also can't use map[byte]T but you can use map[[n]byte]T.
This can sometimes be cumbersome because a lot of functions operate for example on byte whereas some functions return [n]byte (most notably the hash functions in crypto/*).
A sha256 hash for example is [32]byte and not byte so when beginners try to write it to a file for example:
sum := sha256.Sum256(data)
w.Write(sum)
they will get an error. The correct way of is to use
w.Write(sum[:])
However, what is it that you want? Just accessing the string bytewise? You can easily convert a string to byte using:
bytes := byte(str)
but this isn't an array, it's a slice. Also, byte != rune. In case you want to operate on "characters" you need to use rune... not byte.
add a comment |
Arrays are values... slices are more like pointers. That is [n]type is not compatible with type as they are fundamentally two different things. You can get a slice that points to an array by using arr[:] which returns a slice that has arr as it's backing storage.
One way to convert a slice of for example byte to [20]byte is to actually allocate a [20]byte which you can do by using var [20]byte (as it's a value... no make needed) and then copy data into it:
buf := make(byte, 10)
var arr [10]byte
copy(arr[:], buf)
Essentially what a lot of other answers get wrong is that type is NOT an array.
[n]T and T are completely different things!
When using reflect T is not of kind Array but of kind Slice and [n]T is of kind Array.
You also can't use map[byte]T but you can use map[[n]byte]T.
This can sometimes be cumbersome because a lot of functions operate for example on byte whereas some functions return [n]byte (most notably the hash functions in crypto/*).
A sha256 hash for example is [32]byte and not byte so when beginners try to write it to a file for example:
sum := sha256.Sum256(data)
w.Write(sum)
they will get an error. The correct way of is to use
w.Write(sum[:])
However, what is it that you want? Just accessing the string bytewise? You can easily convert a string to byte using:
bytes := byte(str)
but this isn't an array, it's a slice. Also, byte != rune. In case you want to operate on "characters" you need to use rune... not byte.
Arrays are values... slices are more like pointers. That is [n]type is not compatible with type as they are fundamentally two different things. You can get a slice that points to an array by using arr[:] which returns a slice that has arr as it's backing storage.
One way to convert a slice of for example byte to [20]byte is to actually allocate a [20]byte which you can do by using var [20]byte (as it's a value... no make needed) and then copy data into it:
buf := make(byte, 10)
var arr [10]byte
copy(arr[:], buf)
Essentially what a lot of other answers get wrong is that type is NOT an array.
[n]T and T are completely different things!
When using reflect T is not of kind Array but of kind Slice and [n]T is of kind Array.
You also can't use map[byte]T but you can use map[[n]byte]T.
This can sometimes be cumbersome because a lot of functions operate for example on byte whereas some functions return [n]byte (most notably the hash functions in crypto/*).
A sha256 hash for example is [32]byte and not byte so when beginners try to write it to a file for example:
sum := sha256.Sum256(data)
w.Write(sum)
they will get an error. The correct way of is to use
w.Write(sum[:])
However, what is it that you want? Just accessing the string bytewise? You can easily convert a string to byte using:
bytes := byte(str)
but this isn't an array, it's a slice. Also, byte != rune. In case you want to operate on "characters" you need to use rune... not byte.
edited Jun 13 '18 at 15:27
answered Jun 13 '18 at 15:20
mromanmroman
938511
938511
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f8032170%2fhow-to-assign-string-to-bytes-array%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
7
If the length of
stris greater than the length ofarrthen you will get an "index out of range" error.– peterSO
Nov 7 '11 at 4:13