Library contents

R nchar (bytes)

Measure the UTF-8 byte length of text that will be written to a file or sent in a message.

A simple example

nchar (bytes)

  1. Start with "é"
  2. Do this Encode in UTF-8
  3. Result 2 bytes
This single precomposed letter uses the bytes C3 and A9 in hexadecimal.
Lesson.R
value <- "\u00e9"
cat(nchar(enc2utf8(value), type = "bytes"), "\n", sep = "")
Output
2

Syntax

R syntax
nchar(enc2utf8(value), type = "bytes")
Run these examples in R

Save one example at a time as Lesson.R. Use R 4.x.

Rscript --vanilla Lesson.R

Measure a café line on a receipt

A small device accepts an encoded label with a byte limit. Work with its actual encoding to determine what will be transmitted when the text contains more than plain ASCII.

From the programvalue <- "caf\u00e9"
Result5
Lesson.R
value <- "caf\u00e9"
cat(nchar(enc2utf8(value), type = "bytes"), "\n", sep = "")
Output
5

The letter é requires two UTF-8 bytes.

Advertisements

Budget space for a reaction icon

A messaging service budgets storage for reaction icons. Determine how many bytes one emoji occupies in the chosen encoding before reserving space in an outgoing message.

From the programvalue <- "\U0001f600"
Result4
Lesson.R
value <- "\U0001f600"
cat(nchar(enc2utf8(value), type = "bytes"), "\n", sep = "")
Output
4

The emoji occupies four UTF-8 bytes.

Count the bytes on a café tag

The word café ends in a precomposed accented character. Trace a UTF-8 round trip. How many bytes carry this label before it is decoded back to the original text?

Givencafé · UTF-8
Worked result5

What to watch for

Always identify the encoding. String length and encoded byte length can differ.

Documentation for nchar (bytes)