Taskintro
Get the code point of a character
Also called ord, character code, char code, codePointAt, Unicode value of a character, rune value.
Get the number of the code point of a character, not the value of its first byte or its first UTF-16 code unit.
- Evidence
- Code in 10 languages
Task
Get the code point of a character. The function code_point(c) takes a string of exactly one code point and returns its number. For example, code_point("A") is 65, code_point("é") is 233 and code_point("🙂") is 128578 (U+1F642).
The result is the number of the code point, from 1 to 1114111 (U+10FFFF). It is not the value of the first byte of a UTF-8 string, and it is not the value of the first UTF-16 code unit. To visit each character of a longer string, see Iterate over the characters of a string.
Solutions
| Language | Get the code point |
|---|---|
| Python | ord(c) |
| JavaScript, TypeScript | c.codePointAt(0) |
| Java | c.codePointAt(0) |
| C# | Rune.GetRuneAt(c, 0).Value or char.ConvertToUtf32(c, 0) |
| Go | r, _ := utf8.DecodeRuneInString(c) |
| Rust | c.chars().next(), then as u32 |
| C | decode the UTF-8 sequence from its bytes |
| C++ | the same decoding, or std::u32string with U"..." literals |
| Bash | decode the bytes in the C locale |
- Python. "If the argument is a one-character string, return the Unicode code point of that character"1.
- JavaScript and TypeScript.
codePointAtreturns the code point value "of the character starting at the given index"2. The index counts UTF-16 code units. - Java.
codePointAt"Returns the character (Unicode code point) at the specified index"3. - C#.
ConvertToUtf32"Converts the value of a UTF-16 encoded surrogate pair into a Unicode code point"4. - Go.
DecodeRuneInStringgives the first rune of a string and its length in bytes. For an empty string, the docs say: "If s is empty it returns (RuneError, 0)"5. - Rust. A
charis "any ‘Unicode code point’ other than a surrogate code point"6, andas u32gives its number. - C, C++ and Bash. UTF-8 uses "sequences of 1 to 4 octets"7. The first byte gives the length and the high bits. Each continuation byte,
10xxxxxx, gives 6 more bits.
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl.
space,tildeandtab: ASCII characters have 1 byte, and the code point is the value of that byte.two-byte:é(U+00E9) is 233, from 2 UTF-8 bytes.three-byteandcjk:€(U+20AC) is 8364, and日(U+65E5) is 26085. Each one has 3 UTF-8 bytes.combining: U+0301 alone is a character, with the code point 769.astral: U+1F642 is 128578. It has 4 UTF-8 bytes and 2 UTF-16 code units.max: U+10FFFF, 1114111, is the largest code point.
Pitfalls
- Python ord takes only one character.
éaseand U+0301 is 2 code points, soordraisesTypeError. Normalize the text first, see Normalize Unicode text:
print(ord("\u00e9"))
try:
ord("e\u0301")
except TypeError as e:
print(type(e).__name__)
233
TypeError
- JavaScript charCodeAt gives a UTF-16 code unit. For U+1F642,
charCodeAt(0)gives the high surrogate 55357. Also,codePointAt(1)gives the low surrogate 56898, because "the index is still based on UTF-16 code units, not Unicode code points"2:
const s = "\u{1f642}";
console.log(s.charCodeAt(0), s.codePointAt(0), s.codePointAt(1));
55357 128578 56898
- Java charAt gives a char.
charAt"Returns the char value at the specified index"3, and acharis a UTF-16 code unit. So U+1F642 has a length of 2:
public class Main {
public static void main(String[] args) {
String s = "\uD83D\uDE42";
System.out.println((int) s.charAt(0) + " " + s.codePointAt(0) + " " + s.length());
}
}
55357 128578 2
- C# s[1] is the second half of a pair.
(int)s[0]is the high surrogate.ConvertToUtf32(s, 1)starts at the low surrogate, so it throwsArgumentException:
using System;
string s = "\U0001F642";
Console.WriteLine($"{(int)s[0]} {char.ConvertToUtf32(s, 0)}");
try
{
char.ConvertToUtf32(s, 1);
}
catch (ArgumentException e)
{
Console.WriteLine(e.GetType().Name);
}
55357 128578
ArgumentException
- Go s[0] is a byte.
s[0]is 240, the first byte of U+1F642.DecodeRuneInStringgives the rune and its 4 bytes:
package main
import (
"fmt"
"unicode/utf8"
)
func main() {
s := "\U0001F642"
r, size := utf8.DecodeRuneInString(s)
fmt.Println(s[0], r, size)
}
240 128578 4
- Rust: not each u32 is a char. Each
charcan be cast to au32, but "not all valid u32s are valid chars"6.char::from_u32returnsNonefor a surrogate such as 0xD800:
fn main() {
let c = '\u{1F642}';
println!("{}", c as u32);
println!("{:?} {:?}", char::from_u32(0xD800), char::from_u32(0x41));
}
128578
None Some('A')
- C c[0] is a byte. The first byte of U+1F642 is 240. The decoding takes 3 bits from the first byte and 6 bits from each of the 3 continuation bytes:
#include <stdio.h>
#include <string.h>
int main(void) {
const char *c = "\xf0\x9f\x99\x82";
const unsigned char *p = (const unsigned char *)c;
unsigned long cp = ((p[0] & 0x07ul) << 18) | ((p[1] & 0x3ful) << 12) | ((p[2] & 0x3ful) << 6) | (p[3] & 0x3ful);
printf("%zu %d %lu\n", strlen(c), p[0], cp);
return 0;
}
4 240 128578
- C++ std::string holds bytes. U+1F642 is 4 elements of a
std::string. A UTF-32 string literal has the typeconst char32_t[N]8, so each element of astd::u32stringis one code point:
#include <iostream>
#include <string>
int main() {
std::string bytes = "\xf0\x9f\x99\x82";
std::u32string points = U"\U0001F642";
std::cout << bytes.size() << " " << points.size() << " " << static_cast<unsigned long>(points[0]) << "\n";
}
4 1 128578
- Bash printf uses the locale. For
printf '%d' "'x", "the value is the numeric value of the following character, using the current locale"9. In the C locale, the value is only the first byte ofé, 195, not 233. The code takes the low 8 bits with& 255, so that the value is from 0 to 255:
c=$'\xc3\xa9'
(
LC_ALL=C
printf -v b '%d' "'$c"
echo "${#c} $((b & 255))"
)
2 195
Related tasks
- Iterate over the characters of a string: get each character of a string, then its code point.
- Encode and decode UTF-8: the bytes of a code point in UTF-8, and the reverse.
- Convert a string to bytes: the bytes of a whole string.
- Change the case of a string: a change of case that uses the code points of the ASCII letters.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/get-the-code-point-of-a-character/.
def code_point(c: str) -> int:
"""Return the code point of the one character in c."""
return ord(c)
test_code_point.py 28 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/get-the-code-point-of-a-character/.
import pytest
from code_point import code_point
# U+1F642 is one code point, but it is 2 UTF-16 code units and 4 UTF-8 bytes. U+10FFFF is the largest code point.
CASES = {
"upper": ("A", 65),
"lower": ("a", 97),
"digit": ("0", 48),
"space": (" ", 32),
"tab": ("\t", 9),
"tilde": ("~", 126),
"two-byte": ("\u00e9", 233),
"three-byte": ("\u20ac", 8364),
"cjk": ("\u65e5", 26085),
"combining": ("\u0301", 769),
"astral": ("\U0001f642", 128578),
"max": ("\U0010ffff", 1114111),
}
@pytest.mark.parametrize("name", CASES)
def test_code_point(name):
c, want = CASES[name]
assert code_point(c) == want
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-code-point-of-a-character/.
#include "code_point.hpp"
// code_point decodes one UTF-8 sequence. The first byte gives the length and
// the high bits of the code point. Each continuation byte, 10xxxxxx, gives 6
// more bits. c[0] alone would be only the first byte.
std::uint32_t code_point(std::string_view c) {
auto b = [&](std::size_t i) { return static_cast<std::uint32_t>(static_cast<unsigned char>(c[i])); };
std::uint32_t first = b(0);
if (first < 0x80) {
return first;
}
std::size_t n = first < 0xe0 ? 2 : first < 0xf0 ? 3 : 4;
std::uint32_t cp = first & (0x7fu >> n);
for (std::size_t i = 1; i < n; i++) {
cp = (cp << 6) | (b(i) & 0x3f);
}
return cp;
}
code_point.hpp 9 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-code-point-of-a-character/.
#pragma once
#include <cstdint>
#include <string_view>
// code_point returns the code point of the UTF-8 sequence at the start of c.
std::uint32_t code_point(std::string_view c);
test_code_point.cpp 37 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-code-point-of-a-character/.
#include "code_point.hpp"
#include <iostream>
#include <string_view>
static int failures = 0;
static void check(std::string_view name, uint32_t got, uint32_t want) {
if (got != want) {
std::cerr << "case " << name << ": got " << got << ", want " << want << "\n";
failures++;
}
}
// U+1F642 is one code point, but it is 2 UTF-16 code units and 4 UTF-8 bytes. U+10FFFF is the largest code point.
int main() {
check("upper", code_point("A"), 65);
check("lower", code_point("a"), 97);
check("digit", code_point("0"), 48);
check("space", code_point(" "), 32);
check("tab", code_point("\t"), 9);
check("tilde", code_point("~"), 126);
check("two-byte", code_point("\xc3\xa9"), 233);
check("three-byte", code_point("\xe2\x82\xac"), 8364);
check("cjk", code_point("\xe6\x97\xa5"), 26085);
check("combining", code_point("\xcc\x81"), 769);
check("astral", code_point("\xf0\x9f\x99\x82"), 128578);
check("max", code_point("\xf4\x8f\xbf\xbf"), 1114111);
if (failures > 0) {
return 1;
}
std::cout << "all cases pass\n";
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-code-point-of-a-character/.
final class CodePoint {
private CodePoint() {}
// codePoint returns the code point of the one character in c. charAt(0)
// would give only the first UTF-16 code unit of a code point above U+FFFF.
static int codePoint(String c) {
return c.codePointAt(0);
}
}
CodePointTest.java 34 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-code-point-of-a-character/.
import static org.junit.jupiter.api.Assertions.assertEquals;
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 CodePointTest {
// U+1F642 is one code point, but it is 2 UTF-16 code units and 4 UTF-8 bytes. U+10FFFF is the largest code point.
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("upper", "A", 65),
Arguments.of("lower", "a", 97),
Arguments.of("digit", "0", 48),
Arguments.of("space", " ", 32),
Arguments.of("tab", "\t", 9),
Arguments.of("tilde", "~", 126),
Arguments.of("two-byte", "\u00e9", 233),
Arguments.of("three-byte", "\u20ac", 8364),
Arguments.of("cjk", "\u65e5", 26085),
Arguments.of("combining", "\u0301", 769),
Arguments.of("astral", "\ud83d\ude42", 128578),
Arguments.of("max", "\udbff\udfff", 1114111));
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void codePoint(String name, String c, int want) {
assertEquals(want, CodePoint.codePoint(c));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-code-point-of-a-character/.
#include "code_point.h"
// code_point decodes one UTF-8 sequence. The first byte gives the length and
// the high bits of the code point. Each continuation byte, 10xxxxxx, gives 6
// more bits. c[0] alone would be only the first byte.
uint32_t code_point(const char *c) {
const unsigned char *p = (const unsigned char *)c;
if (p[0] < 0x80) {
return p[0];
}
if (p[0] < 0xe0) {
return ((uint32_t)(p[0] & 0x1f) << 6) | (p[1] & 0x3f);
}
if (p[0] < 0xf0) {
return ((uint32_t)(p[0] & 0x0f) << 12) | ((uint32_t)(p[1] & 0x3f) << 6) | (p[2] & 0x3f);
}
return ((uint32_t)(p[0] & 0x07) << 18) | ((uint32_t)(p[1] & 0x3f) << 12) | ((uint32_t)(p[2] & 0x3f) << 6) |
(p[3] & 0x3f);
}
code_point.h 11 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-code-point-of-a-character/.
#ifndef CODE_POINT_H
#define CODE_POINT_H
#include <stdint.h>
// code_point returns the code point of the UTF-8 sequence at the start of c.
uint32_t code_point(const char *c);
#endif
test_code_point.c 36 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-code-point-of-a-character/.
#include "code_point.h"
#include <stdio.h>
static int failures = 0;
static void check(const char *name, uint32_t got, uint32_t want) {
if (got != want) {
fprintf(stderr, "case %s: got %lu, want %lu\n", name, (unsigned long)got, (unsigned long)want);
failures++;
}
}
// U+1F642 is one code point, but it is 2 UTF-16 code units and 4 UTF-8 bytes. U+10FFFF is the largest code point.
int main(void) {
check("upper", code_point("A"), 65);
check("lower", code_point("a"), 97);
check("digit", code_point("0"), 48);
check("space", code_point(" "), 32);
check("tab", code_point("\t"), 9);
check("tilde", code_point("~"), 126);
check("two-byte", code_point("\xc3\xa9"), 233);
check("three-byte", code_point("\xe2\x82\xac"), 8364);
check("cjk", code_point("\xe6\x97\xa5"), 26085);
check("combining", code_point("\xcc\x81"), 769);
check("astral", code_point("\xf0\x9f\x99\x82"), 128578);
check("max", code_point("\xf4\x8f\xbf\xbf"), 1114111);
if (failures > 0) {
return 1;
}
printf("all cases pass\n");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-code-point-of-a-character/.
using System.Text;
public static class CodePoints
{
// CodePoint returns the code point of the one character in c. (int)c[0]
// would give only the first UTF-16 code unit of a code point above U+FFFF.
public static int CodePoint(string c)
{
return Rune.GetRuneAt(c, 0).Value;
}
}
CodePointTests.cs 32 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-code-point-of-a-character/.
using Xunit;
public sealed class CodePointTests
{
// U+1F642 is one code point, but it is 2 UTF-16 code units and 4 UTF-8 bytes. U+10FFFF is the largest code point.
public static TheoryData<string, string, int> Cases => new()
{
{ "upper", "A", 65 },
{ "lower", "a", 97 },
{ "digit", "0", 48 },
{ "space", " ", 32 },
{ "tab", "\t", 9 },
{ "tilde", "~", 126 },
{ "two-byte", "\u00e9", 233 },
{ "three-byte", "\u20ac", 8364 },
{ "cjk", "\u65e5", 26085 },
{ "combining", "\u0301", 769 },
{ "astral", "\U0001f642", 128578 },
{ "max", "\U0010ffff", 1114111 },
};
[Theory]
[MemberData(nameof(Cases))]
public void CodePoint(string name, string c, int want)
{
Assert.NotNull(name);
Assert.Equal(want, CodePoints.CodePoint(c));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-code-point-of-a-character/.
// codePoint returns the code point of the one character in c. charCodeAt(0)
// would give only the first UTF-16 code unit of a code point above U+FFFF.
export function codePoint(c) {
return c.codePointAt(0);
}
code_point.test.js 29 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-code-point-of-a-character/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { codePoint } from "./code_point.js";
// U+1F642 is one code point, but it is 2 UTF-16 code units and 4 UTF-8 bytes. U+10FFFF is the largest code point.
const cases = [
["upper", "A", 65],
["lower", "a", 97],
["digit", "0", 48],
["space", " ", 32],
["tab", "\t", 9],
["tilde", "~", 126],
["two-byte", "\u00e9", 233],
["three-byte", "\u20ac", 8364],
["cjk", "\u65e5", 26085],
["combining", "\u0301", 769],
["astral", "\u{1f642}", 128578],
["max", "\u{10ffff}", 1114111],
];
for (const [name, c, want] of cases) {
test(name, () => {
assert.equal(codePoint(c), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-code-point-of-a-character/.
// codePoint returns the code point of the one character in c. charCodeAt(0)
// would give only the first UTF-16 code unit of a code point above U+FFFF.
export function codePoint(c: string): number {
return c.codePointAt(0)!;
}
code_point.test.ts 29 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-code-point-of-a-character/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { codePoint } from "./code_point.ts";
// U+1F642 is one code point, but it is 2 UTF-16 code units and 4 UTF-8 bytes. U+10FFFF is the largest code point.
const cases: [string, string, number][] = [
["upper", "A", 65],
["lower", "a", 97],
["digit", "0", 48],
["space", " ", 32],
["tab", "\t", 9],
["tilde", "~", 126],
["two-byte", "\u00e9", 233],
["three-byte", "\u20ac", 8364],
["cjk", "\u65e5", 26085],
["combining", "\u0301", 769],
["astral", "\u{1f642}", 128578],
["max", "\u{10ffff}", 1114111],
];
for (const [name, c, want] of cases) {
test(name, () => {
assert.equal(codePoint(c), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-code-point-of-a-character/.
// Package codepoint gives the code point of a character.
package codepoint
import "unicode/utf8"
// CodePoint returns the code point of the one character in c. c[0] would give
// only the first byte of the UTF-8 sequence.
func CodePoint(c string) int {
r, _ := utf8.DecodeRuneInString(c)
return int(r)
}
code_point_test.go 33 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-code-point-of-a-character/.
package codepoint
import "testing"
// U+1F642 is one code point, but it is 2 UTF-16 code units and 4 UTF-8 bytes. U+10FFFF is the largest code point.
var cases = []struct {
name, c string
want int
}{
{"upper", "A", 65},
{"lower", "a", 97},
{"digit", "0", 48},
{"space", " ", 32},
{"tab", "\t", 9},
{"tilde", "~", 126},
{"two-byte", "\u00e9", 233},
{"three-byte", "\u20ac", 8364},
{"cjk", "\u65e5", 26085},
{"combining", "\u0301", 769},
{"astral", "\U0001f642", 128578},
{"max", "\U0010ffff", 1114111},
}
func TestCodePoint(t *testing.T) {
for _, c := range cases {
if got := CodePoint(c.c); got != c.want {
t.Errorf("%s: got %d, want %d", c.name, got, c.want)
}
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-code-point-of-a-character/.
/// Returns the code point of the one character in `c`. `c.as_bytes()[0]`
/// would give only the first byte of the UTF-8 sequence.
pub fn code_point(c: &str) -> u32 {
c.chars().next().map_or(0, u32::from)
}
tests/code_point_test.rs 26 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-code-point-of-a-character/.
use algo_get_the_code_point_of_a_character::code_point;
// U+1F642 is one code point, but it is 2 UTF-16 code units and 4 UTF-8 bytes. U+10FFFF is the largest code point.
#[test]
fn cases() {
let cases: [(&str, &str, u32); 12] = [
("upper", "A", 65),
("lower", "a", 97),
("digit", "0", 48),
("space", " ", 32),
("tab", "\t", 9),
("tilde", "~", 126),
("two-byte", "\u{e9}", 233),
("three-byte", "\u{20ac}", 8364),
("cjk", "\u{65e5}", 26085),
("combining", "\u{301}", 769),
("astral", "\u{1f642}", 128578),
("max", "\u{10ffff}", 1114111),
];
for (name, c, want) in cases {
assert_eq!(code_point(c), want, "{name}");
}
}
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/get-the-code-point-of-a-character/.
# code_point C: prints the code point of the one character in C. In the C
# locale, printf '%d' "'x" gives the value of one byte, so the function decodes
# the UTF-8 sequence from its bytes.
code_point() {
(
LC_ALL=C
c=$1
n=${#c}
printf -v b0 '%d' "'${c:0:1}"
((b0 < 0)) && ((b0 += 256))
if ((n == 1)); then
echo "$b0"
return
fi
((cp = b0 & (0x7f >> n)))
for ((i = 1; i < n; i++)); do
printf -v b '%d' "'${c:i:1}"
((b < 0)) && ((b += 256))
((cp = (cp << 6) | (b & 0x3f)))
done
echo "$cp"
)
}
test_code_point.bats 28 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/get-the-code-point-of-a-character/.
bats_require_minimum_version 1.5.0
setup() {
source "$BATS_TEST_DIRNAME/code_point.sh"
}
check() { # check C WANT
run code_point "$1"
[ "$status" -eq 0 ]
[ "$output" = "$2" ]
}
# Each argument is a string of UTF-8 bytes for one code point.
@test "upper" { check 'A' 65; }
@test "lower" { check 'a' 97; }
@test "digit" { check '0' 48; }
@test "space" { check ' ' 32; }
@test "tab" { check $'\t' 9; }
@test "tilde" { check '~' 126; }
@test "two-byte" { check $'\xc3\xa9' 233; }
@test "three-byte" { check $'\xe2\x82\xac' 8364; }
@test "cjk" { check $'\xe6\x97\xa5' 26085; }
@test "combining" { check $'\xcc\x81' 769; }
@test "astral" { check $'\xf0\x9f\x99\x82' 128578; }
@test "max" { check $'\xf4\x8f\xbf\xbf' 1114111; }
References
- The Python Standard Library, Built-in Functions, ord()
- MDN Web Docs, String.prototype.codePointAt(), Description
- Java SE 25 API, Class String, charAt(int), codePointAt(int)
- .NET API reference, Char.ConvertToUtf32 method, Overloads, Exceptions
- Go standard library, package unicode/utf8, DecodeRuneInString
- Rust standard library, primitive type char, Validity and Layout, from_u32
- RFC 3629, UTF-8, a transformation format of ISO 10646, 3. UTF-8 definition
- cppreference.com, String literal, Explanation
- Bash Reference Manual, 4.2 Bash Builtin Commands, printf
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (bash) | I0 not checked yet |
|
| Code (c) | I0 not checked yet |
|
| Code (cpp) | I0 not checked yet |
|
| Code (csharp) | I0 not checked yet |
|
| Code (go) | I0 not checked yet |
|
| Code (java) | I0 not checked yet |
|
| Code (javascript) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Code (rust) | I0 not checked yet |
|
| Code (typescript) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag QSJE4Y Edit this page History Report an error Markdown