Logo

Programming-Idioms

  • JS
  • Ruby
  • Python
  • Go
  • Elixir
  • Pascal

Idiom #304 Encode string into UTF-8 bytes

Create the array of bytes data by encoding the string s in UTF-8.

var
  data: pbyte absolute s;

Declare data as a variable that points to the same absolute address as the string s.
The type pbyte (pointer to a byte) can be accessed as an array, so data[0] is the first byte of the string.
const data = new TextEncoder().encode(s);
data = s.bytes

UTF-8 is the default string encoding.
data = s.encode('utf8')
data := []byte(s)

In Go, it is idiomatic that strings are already encoded in UTF-8. So we can grab their raw bytes directly.
using System.Text;
byte[] data = Encoding.UTF8.GetBytes(s);

New implementation...