Programming Search⌘K

Taskintro

Convert a string to bytes

Also called string to byte array, encode a string, getBytes, TextEncoder, as_bytes, byte array of a string.

Get the bytes of a string in UTF-8, and give the encoding each time so that the result does not change with the platform.

Task

Convert a string to bytes. The function to_bytes(s) returns the bytes of s in UTF-8, in order, each from 0 to 255. For example, to_bytes("abc") is [97, 98, 99], and to_bytes("é") is [195, 169].

A string is text, and bytes are its form in a file, on a network or in memory. The same text has different bytes in different encodings, so the code gives the encoding each time. To write the encoder by hand, see Encode and decode UTF-8.

Solutions

Language The UTF-8 bytes of a string
Python s.encode("utf-8")
JavaScript, TypeScript new TextEncoder().encode(s)
Java s.getBytes(StandardCharsets.UTF_8)
C# Encoding.UTF8.GetBytes(s)
Go []byte(s)
Rust s.as_bytes(), or s.as_bytes().to_vec() for a copy
C the char array of the string, read as unsigned char
C++ std::vector<std::uint8_t>(s.begin(), s.end())
Bash printf '%d' "'x" for each byte, in the C locale
  • Python. str.encode returns "the string encoded to bytes"1. The result is a bytes object.
  • JavaScript and TypeScript. TextEncoder.encode returns "a Uint8Array containing the string encoded using UTF-8"2. It has no other encoding.
  • Java and C#. Give the charset: StandardCharsets.UTF_8 and Encoding.UTF8.
  • Go. The conversion "yields a non-nil slice whose successive elements are the bytes of the string"3. A Go string holds the bytes, so the conversion copies them.
  • Rust. A str is always UTF-8, so as_bytes gives its bytes with no copy.
  • C and C++. A string literal in the source is already bytes. The impls in this node expect UTF-8 strings.
  • Bash. The C locale makes ${s:i:1} one byte. The code takes the low 8 bits with & 255.

Edge cases

The cases are in cases/basic.jsonl and cases/edge.jsonl.

  • empty: the empty string gives an empty list.
  • control: a tab and a line feed are the bytes 9 and 10.
  • two-byte and latin-1-max: é (U+00E9) is [195, 169], and U+00FF is [195, 191]. In Latin-1, each one would be 1 byte.
  • three-byte and bom: € (U+20AC) is [226, 130, 172], and U+FEFF is [239, 187, 191].
  • astral: U+1F642 is 4 bytes, [240, 159, 153, 130].
  • combining: e and U+0301 are [101, 204, 129]. This is not the same as the 2 bytes of é as one code point. See Normalize Unicode text.
  • mixed: the bytes of each code point follow the bytes of the code point before it.

Pitfalls

  • Python str of bytes is not a decode. "Passing a bytes object to str() without the encoding or errors arguments falls under the first case of returning the informal string representation"1. So str(b) gives b'abc'. Use b.decode("utf-8"). Also, the encoding changes the length:
b = "abc".encode("utf-8")
print(str(b))
print(b.decode("utf-8"))
print(len("\u00e9".encode("latin-1")), len("\u00e9".encode("utf-8")))
Output
b'abc'
abc
1 2
  • JavaScript length is not the number of bytes. length "returns the number of code units in the string"4. U+1F642 is 2 code units and 4 UTF-8 bytes:
const s = "\u{1f642}";
console.log(s.length, new TextEncoder().encode(s).length);
Output
2 4
  • Java getBytes() uses the default charset, and a byte is signed. getBytes() "Encodes this String into a sequence of bytes using the default charset"5, so give the charset. Also, byte is one of the integral types "whose values are 8-bit, 16-bit, 32-bit and 64-bit signed two's-complement integers, respectively"6. The first byte of é is -61, and b & 0xff is 195:
import java.nio.charset.StandardCharsets;

public class Main {
  public static void main(String[] args) {
    byte[] b = "\u00e9".getBytes(StandardCharsets.UTF_8);
    System.out.println(b[0] + " " + (b[0] & 0xff));
  }
}
Output
-61 195
  • C# Encoding.Unicode is UTF-16. The property "Gets an encoding for the UTF-16 format using the little endian byte order"7. So é is the 2 bytes E9 and 00, not C3 and A9:
using System;
using System.Text;

string s = "\u00e9";
Console.WriteLine(BitConverter.ToString(Encoding.Unicode.GetBytes(s)));
Console.WriteLine(BitConverter.ToString(Encoding.UTF8.GetBytes(s)));
Output
E9-00
C3-A9
  • Go []byte(s) is a copy. A change to the slice does not change the string:
package main

import "fmt"

func main() {
	s := "jam"
	b := []byte(s)
	b[0] = 'J'
	fmt.Println(s, string(b))
}
Output
jam Jam
  • Rust: not each byte sequence is a String. String::from_utf8 returns an error for bytes that are not UTF-8. from_utf8_lossy() "will replace any invalid UTF-8 sequences with U+FFFD REPLACEMENT CHARACTER"8, and 65533 is U+FFFD:
fn main() {
    let bad = vec![0x61, 0xff];
    println!("{}", String::from_utf8(bad.clone()).is_err());
    let text = String::from_utf8_lossy(&bad);
    let points: Vec<u32> = text.chars().map(u32::from).collect();
    println!("{:?}", points);
}
Output
true
[97, 65533]
  • C sizeof counts the NUL. For a string literal, the size N is "the size of the string in code units of the execution narrow encoding, including the null terminator"9. So sizeof gives 3 for é, and strlen gives 2:
#include <stdio.h>
#include <string.h>

int main(void) {
    printf("%zu %zu\n", sizeof "\xc3\xa9", strlen("\xc3\xa9"));
    return 0;
}
Output
3 2
  • C++ std::string from a literal stops at a NUL byte. The constructor from a literal "stops at the first null character"10. Use the s suffix to keep each byte:
#include <iostream>
#include <string>

using namespace std::string_literals;

int main() {
    std::string a = "a\0b";
    std::string b = "a\0b"s;
    std::cout << a.size() << " " << b.size() << "\n";
}
Output
1 3
  • Bash echo adds a byte. echo writes "the args, separated by spaces, terminated with a newline"11. So wc -c counts 4 bytes for abc. Use printf '%s':
s='abc'
echo "$s" | wc -c | tr -d ' '
printf '%s' "$s" | wc -c | tr -d ' '
Output
4
3

Code

The build runs the native tests of each language in a pinned toolchain.

to_bytes.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/convert-a-string-to-bytes/.


def to_bytes(s: str) -> bytes:
    """Return the UTF-8 bytes of s.

    The encoding is given each time, so the result does not depend on the
    platform.
    """
    return s.encode("utf-8")
test_to_bytes.py 28 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/convert-a-string-to-bytes/.

import pytest

from to_bytes import to_bytes

# The encoding is UTF-8. U+00E9 is 2 bytes, U+20AC is 3 bytes and U+1F642 is 4 bytes. In Latin-1, U+00FF would be 1 byte.
CASES = {
    "ascii": ("abc", [97, 98, 99]),
    "letter": ("A", [65]),
    "punct": ("hi!", [104, 105, 33]),
    "empty": ("", []),
    "control": ("\t\n", [9, 10]),
    "two-byte": ("\u00e9", [195, 169]),
    "latin-1-max": ("\u00ff", [195, 191]),
    "three-byte": ("\u20ac", [226, 130, 172]),
    "bom": ("\ufeff", [239, 187, 191]),
    "astral": ("\U0001f642", [240, 159, 153, 130]),
    "combining": ("e\u0301", [101, 204, 129]),
    "mixed": ("a\u00e9\U0001f642", [97, 195, 169, 240, 159, 153, 130]),
}


@pytest.mark.parametrize("name", CASES)
def test_to_bytes(name):
    s, want = CASES[name]
    assert to_bytes(s) == bytes(want)
to_bytes.cppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/convert-a-string-to-bytes/.

#include "to_bytes.hpp"

// A std::string holds bytes, so the function copies them as std::uint8_t.
std::vector<std::uint8_t> to_bytes(std::string_view s) {
    return {s.begin(), s.end()};
}
to_bytes.hpp 10 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/convert-a-string-to-bytes/.
#pragma once

#include <cstdint>
#include <string_view>
#include <vector>

// to_bytes returns the bytes of the UTF-8 string s.
std::vector<std::uint8_t> to_bytes(std::string_view s);
test_to_bytes.cpp 39 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/convert-a-string-to-bytes/.

#include "to_bytes.hpp"

#include <cstdint>
#include <iostream>
#include <string_view>
#include <vector>

static int failures = 0;

static void check(std::string_view name, std::string_view s, const std::vector<std::uint8_t> &want) {
    if (to_bytes(s) != want) {
        std::cerr << "case " << name << " fails\n";
        failures++;
    }
}

// The encoding is UTF-8. U+00E9 is 2 bytes, U+20AC is 3 bytes and U+1F642 is 4 bytes. In Latin-1, U+00FF would be 1 byte.
int main() {
    check("ascii", "abc", {97, 98, 99});
    check("letter", "A", {65});
    check("punct", "hi!", {104, 105, 33});
    check("empty", "", {});
    check("control", "\t\n", {9, 10});
    check("two-byte", "\xc3\xa9", {195, 169});
    check("latin-1-max", "\xc3\xbf", {195, 191});
    check("three-byte", "\xe2\x82\xac", {226, 130, 172});
    check("bom", "\xef\xbb\xbf", {239, 187, 191});
    check("astral", "\xf0\x9f\x99\x82", {240, 159, 153, 130});
    check("combining", "e\xcc\x81", {101, 204, 129});
    check("mixed", "a\xc3\xa9\xf0\x9f\x99\x82", {97, 195, 169, 240, 159, 153, 130});
    if (failures > 0) {
        return 1;
    }
    std::cout << "all cases pass\n";
    return 0;
}
ToBytes.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/convert-a-string-to-bytes/.

import java.nio.charset.StandardCharsets;

final class ToBytes {
  private ToBytes() {}

  // toBytes returns the UTF-8 bytes of s. The charset is given each time, so
  // the result does not depend on the default charset.
  static byte[] toBytes(String s) {
    return s.getBytes(StandardCharsets.UTF_8);
  }
}
ToBytesTest.java 39 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/convert-a-string-to-bytes/.

import static org.junit.jupiter.api.Assertions.assertArrayEquals;

import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

class ToBytesTest {
  // The encoding is UTF-8. U+00E9 is 2 bytes, U+20AC is 3 bytes and U+1F642 is 4 bytes. In Latin-1, U+00FF would be 1 byte. A Java byte is signed, so the test compares b & 0xff.
  static Stream<Arguments> cases() {
    return Stream.of(
        Arguments.of("ascii", "abc", new int[] {97, 98, 99}),
        Arguments.of("letter", "A", new int[] {65}),
        Arguments.of("punct", "hi!", new int[] {104, 105, 33}),
        Arguments.of("empty", "", new int[] {}),
        Arguments.of("control", "\t\n", new int[] {9, 10}),
        Arguments.of("two-byte", "\u00e9", new int[] {195, 169}),
        Arguments.of("latin-1-max", "\u00ff", new int[] {195, 191}),
        Arguments.of("three-byte", "\u20ac", new int[] {226, 130, 172}),
        Arguments.of("bom", "\ufeff", new int[] {239, 187, 191}),
        Arguments.of("astral", "\ud83d\ude42", new int[] {240, 159, 153, 130}),
        Arguments.of("combining", "e\u0301", new int[] {101, 204, 129}),
        Arguments.of("mixed", "a\u00e9\ud83d\ude42", new int[] {97, 195, 169, 240, 159, 153, 130}));
  }

  @ParameterizedTest(name = "{0}")
  @MethodSource("cases")
  void toBytes(String name, String s, int[] want) {
    byte[] got = ToBytes.toBytes(s);
    int[] values = new int[got.length];
    for (int i = 0; i < got.length; i++) {
      values[i] = got[i] & 0xff;
    }
    assertArrayEquals(want, values);
  }
}
to_bytes.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/convert-a-string-to-bytes/.

#include "to_bytes.h"

#include <stdlib.h>
#include <string.h>

// A C string is already a sequence of bytes, so the function copies them as
// unsigned char. strlen counts bytes, not code points.
unsigned char *to_bytes(const char *s, size_t *n) {
    size_t len = strlen(s);
    // malloc(0) can return NULL, so the array has at least 1 byte.
    unsigned char *out = malloc(len > 0 ? len : 1);
    *n = 0;
    if (out == NULL) {
        return NULL;
    }
    memcpy(out, s, len);
    *n = len;
    return out;
}
to_bytes.h 12 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/convert-a-string-to-bytes/.
#ifndef TO_BYTES_H
#define TO_BYTES_H

#include <stddef.h>

// to_bytes returns a new array of the *n bytes of the UTF-8 string s, without
// the terminating NUL, or NULL if there is no memory. Free it with free.
unsigned char *to_bytes(const char *s, size_t *n);

#endif
test_to_bytes.c 42 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/convert-a-string-to-bytes/.

#include "to_bytes.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static int failures = 0;

// check compares the n bytes of got with want, and then frees got.
static void check(const char *name, const char *s, const unsigned char *want, size_t n) {
    size_t k = 0;
    unsigned char *got = to_bytes(s, &k);
    if (got == NULL || k != n || (n > 0 && memcmp(got, want, n) != 0)) {
        fprintf(stderr, "case %s: got %zu bytes, want %zu\n", name, k, n);
        failures++;
    }
    free(got);
}

// The encoding is UTF-8. U+00E9 is 2 bytes, U+20AC is 3 bytes and U+1F642 is 4 bytes. In Latin-1, U+00FF would be 1 byte.
int main(void) {
    check("ascii", "abc", (const unsigned char[]){97, 98, 99}, 3);
    check("letter", "A", (const unsigned char[]){65}, 1);
    check("punct", "hi!", (const unsigned char[]){104, 105, 33}, 3);
    check("empty", "", NULL, 0);
    check("control", "\t\n", (const unsigned char[]){9, 10}, 2);
    check("two-byte", "\xc3\xa9", (const unsigned char[]){195, 169}, 2);
    check("latin-1-max", "\xc3\xbf", (const unsigned char[]){195, 191}, 2);
    check("three-byte", "\xe2\x82\xac", (const unsigned char[]){226, 130, 172}, 3);
    check("bom", "\xef\xbb\xbf", (const unsigned char[]){239, 187, 191}, 3);
    check("astral", "\xf0\x9f\x99\x82", (const unsigned char[]){240, 159, 153, 130}, 4);
    check("combining", "e\xcc\x81", (const unsigned char[]){101, 204, 129}, 3);
    check("mixed", "a\xc3\xa9\xf0\x9f\x99\x82", (const unsigned char[]){97, 195, 169, 240, 159, 153, 130}, 7);
    if (failures > 0) {
        return 1;
    }
    printf("all cases pass\n");
    return 0;
}
StringBytes.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/convert-a-string-to-bytes/.

using System.Text;

public static class StringBytes
{
    // ToBytes returns the UTF-8 bytes of s. Encoding.Unicode would give
    // UTF-16 bytes.
    public static byte[] ToBytes(string s)
    {
        return Encoding.UTF8.GetBytes(s);
    }
}
ToBytesTests.cs 32 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/convert-a-string-to-bytes/.

using Xunit;

public sealed class ToBytesTests
{
    // The encoding is UTF-8. U+00E9 is 2 bytes, U+20AC is 3 bytes and U+1F642 is 4 bytes. In Latin-1, U+00FF would be 1 byte.
    public static TheoryData<string, string, byte[]> Cases => new()
    {
        { "ascii", "abc", new byte[] { 97, 98, 99 } },
        { "letter", "A", new byte[] { 65 } },
        { "punct", "hi!", new byte[] { 104, 105, 33 } },
        { "empty", "", new byte[] {  } },
        { "control", "\t\n", new byte[] { 9, 10 } },
        { "two-byte", "\u00e9", new byte[] { 195, 169 } },
        { "latin-1-max", "\u00ff", new byte[] { 195, 191 } },
        { "three-byte", "\u20ac", new byte[] { 226, 130, 172 } },
        { "bom", "\ufeff", new byte[] { 239, 187, 191 } },
        { "astral", "\U0001f642", new byte[] { 240, 159, 153, 130 } },
        { "combining", "e\u0301", new byte[] { 101, 204, 129 } },
        { "mixed", "a\u00e9\U0001f642", new byte[] { 97, 195, 169, 240, 159, 153, 130 } },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void ToBytes(string name, string s, byte[] want)
    {
        Assert.NotNull(name);
        Assert.Equal(want, StringBytes.ToBytes(s));
    }
}
to_bytes.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/convert-a-string-to-bytes/.

// toBytes returns the UTF-8 bytes of s. TextEncoder always encodes to UTF-8.
export function toBytes(s) {
  return new TextEncoder().encode(s);
}
to_bytes.test.js 29 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/convert-a-string-to-bytes/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { toBytes } from "./to_bytes.js";

// The encoding is UTF-8. U+00E9 is 2 bytes, U+20AC is 3 bytes and U+1F642 is 4 bytes. In Latin-1, U+00FF would be 1 byte.
const cases = [
  ["ascii", "abc", [97, 98, 99]],
  ["letter", "A", [65]],
  ["punct", "hi!", [104, 105, 33]],
  ["empty", "", []],
  ["control", "\t\n", [9, 10]],
  ["two-byte", "\u00e9", [195, 169]],
  ["latin-1-max", "\u00ff", [195, 191]],
  ["three-byte", "\u20ac", [226, 130, 172]],
  ["bom", "\ufeff", [239, 187, 191]],
  ["astral", "\u{1f642}", [240, 159, 153, 130]],
  ["combining", "e\u0301", [101, 204, 129]],
  ["mixed", "a\u00e9\u{1f642}", [97, 195, 169, 240, 159, 153, 130]],
];

for (const [name, s, want] of cases) {
  test(name, () => {
    assert.deepEqual(Array.from(toBytes(s)), want);
  });
}
to_bytes.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/convert-a-string-to-bytes/.

// toBytes returns the UTF-8 bytes of s. TextEncoder always encodes to UTF-8.
export function toBytes(s: string): Uint8Array {
  return new TextEncoder().encode(s);
}
to_bytes.test.ts 29 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/convert-a-string-to-bytes/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { toBytes } from "./to_bytes.ts";

// The encoding is UTF-8. U+00E9 is 2 bytes, U+20AC is 3 bytes and U+1F642 is 4 bytes. In Latin-1, U+00FF would be 1 byte.
const cases: [string, string, number[]][] = [
  ["ascii", "abc", [97, 98, 99]],
  ["letter", "A", [65]],
  ["punct", "hi!", [104, 105, 33]],
  ["empty", "", []],
  ["control", "\t\n", [9, 10]],
  ["two-byte", "\u00e9", [195, 169]],
  ["latin-1-max", "\u00ff", [195, 191]],
  ["three-byte", "\u20ac", [226, 130, 172]],
  ["bom", "\ufeff", [239, 187, 191]],
  ["astral", "\u{1f642}", [240, 159, 153, 130]],
  ["combining", "e\u0301", [101, 204, 129]],
  ["mixed", "a\u00e9\u{1f642}", [97, 195, 169, 240, 159, 153, 130]],
];

for (const [name, s, want] of cases) {
  test(name, () => {
    assert.deepEqual(Array.from(toBytes(s)), want);
  });
}
to_bytes.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/convert-a-string-to-bytes/.

// Package tobytes gives the bytes of a string.
package tobytes

// ToBytes returns the UTF-8 bytes of s. A Go string holds bytes, and the
// conversion copies them.
func ToBytes(s string) []byte {
	return []byte(s)
}
to_bytes_test.go 36 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/convert-a-string-to-bytes/.

package tobytes

import (
	"bytes"
	"testing"
)

// The encoding is UTF-8. U+00E9 is 2 bytes, U+20AC is 3 bytes and U+1F642 is 4 bytes. In Latin-1, U+00FF would be 1 byte.
var cases = []struct {
	name, s string
	want    []byte
}{
	{"ascii", "abc", []byte{97, 98, 99}},
	{"letter", "A", []byte{65}},
	{"punct", "hi!", []byte{104, 105, 33}},
	{"empty", "", []byte{}},
	{"control", "\t\n", []byte{9, 10}},
	{"two-byte", "\u00e9", []byte{195, 169}},
	{"latin-1-max", "\u00ff", []byte{195, 191}},
	{"three-byte", "\u20ac", []byte{226, 130, 172}},
	{"bom", "\ufeff", []byte{239, 187, 191}},
	{"astral", "\U0001f642", []byte{240, 159, 153, 130}},
	{"combining", "e\u0301", []byte{101, 204, 129}},
	{"mixed", "a\u00e9\U0001f642", []byte{97, 195, 169, 240, 159, 153, 130}},
}

func TestToBytes(t *testing.T) {
	for _, c := range cases {
		if got := ToBytes(c.s); !bytes.Equal(got, c.want) {
			t.Errorf("%s: got %v, want %v", c.name, got, c.want)
		}
	}
}
to_bytes.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/convert-a-string-to-bytes/.

/// Returns the UTF-8 bytes of `s`. A `str` is UTF-8, so `as_bytes` gives its
/// bytes, and `to_vec` copies them.
pub fn to_bytes(s: &str) -> Vec<u8> {
    s.as_bytes().to_vec()
}
tests/to_bytes_test.rs 26 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/convert-a-string-to-bytes/.

use algo_convert_a_string_to_bytes::to_bytes;

// The encoding is UTF-8. U+00E9 is 2 bytes, U+20AC is 3 bytes and U+1F642 is 4 bytes. In Latin-1, U+00FF would be 1 byte.
#[test]
fn cases() {
    let cases: [(&str, &str, &[u8]); 12] = [
        ("ascii", "abc", &[97, 98, 99]),
        ("letter", "A", &[65]),
        ("punct", "hi!", &[104, 105, 33]),
        ("empty", "", &[]),
        ("control", "\t\n", &[9, 10]),
        ("two-byte", "\u{e9}", &[195, 169]),
        ("latin-1-max", "\u{ff}", &[195, 191]),
        ("three-byte", "\u{20ac}", &[226, 130, 172]),
        ("bom", "\u{feff}", &[239, 187, 191]),
        ("astral", "\u{1f642}", &[240, 159, 153, 130]),
        ("combining", "e\u{301}", &[101, 204, 129]),
        ("mixed", "a\u{e9}\u{1f642}", &[97, 195, 169, 240, 159, 153, 130]),
    ];
    for (name, s, want) in cases {
        assert_eq!(to_bytes(s), want, "{name}");
    }
}
to_bytes.shI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/convert-a-string-to-bytes/.

# to_bytes S: prints the UTF-8 bytes of S as numbers, with one space between
# them. In the C locale, ${s:i:1} is one byte, and printf '%d' "'x" gives its
# value. The value is taken from 0 to 255 with & 255.
to_bytes() {
  (
    LC_ALL=C
    s=$1
    out=
    for ((i = 0; i < ${#s}; i++)); do
      printf -v b '%d' "'${s:i:1}"
      out+="${out:+ }$((b & 255))"
    done
    printf '%s' "$out"
  )
}
test_to_bytes.bats 28 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/convert-a-string-to-bytes/.

bats_require_minimum_version 1.5.0

setup() {
  source "$BATS_TEST_DIRNAME/to_bytes.sh"
}

check() { # check S WANT
  run to_bytes "$1"
  [ "$status" -eq 0 ]
  [ "$output" = "$2" ]
}

# Each argument is a string of UTF-8 bytes, and the output is the byte values with one space between them.
@test "ascii" { check 'abc' '97 98 99'; }
@test "letter" { check 'A' '65'; }
@test "punct" { check 'hi!' '104 105 33'; }
@test "empty" { check '' ''; }
@test "control" { check $'\t\n' '9 10'; }
@test "two-byte" { check $'\xc3\xa9' '195 169'; }
@test "latin-1-max" { check $'\xc3\xbf' '195 191'; }
@test "three-byte" { check $'\xe2\x82\xac' '226 130 172'; }
@test "bom" { check $'\xef\xbb\xbf' '239 187 191'; }
@test "astral" { check $'\xf0\x9f\x99\x82' '240 159 153 130'; }
@test "combining" { check $'e\xcc\x81' '101 204 129'; }
@test "mixed" { check $'a\xc3\xa9\xf0\x9f\x99\x82' '97 195 169 240 159 153 130'; }

References

  1. The Python Standard Library, Built-in Types, str(), str.encode
  2. MDN Web Docs, TextEncoder, Instance methods
  3. The Go Programming Language Specification, Conversions to and from a string type
  4. MDN Web Docs, String.length, Description
  5. Java SE 25 API, Class String, getBytes()
  6. The Java Language Specification, Java SE 25 Edition, 4.2 Primitive Types and Values
  7. .NET API reference, Encoding.Unicode property, Definition
  8. Rust standard library, struct String, from_utf8_lossy
  9. cppreference.com, String literals (C), Explanation
  10. cppreference.com, std::basic_string constructor, Notes
  11. Bash Reference Manual, 4.2 Bash Builtin Commands, echo

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (bash)I0 not checked yet
  • the tests did not run in this build
Code (c)I0 not checked yet
  • the tests did not run in this build
Code (cpp)I0 not checked yet
  • the tests did not run in this build
Code (csharp)I0 not checked yet
  • the tests did not run in this build
Code (go)I0 not checked yet
  • the tests did not run in this build
Code (java)I0 not checked yet
  • the tests did not run in this build
Code (javascript)I0 not checked yet
  • the tests did not run in this build
Code (python)I0 not checked yet
  • the tests did not run in this build
Code (rust)I0 not checked yet
  • the tests did not run in this build
Code (typescript)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source