Library contents

R readBin and writeBin

Write a small binary payload and read one byte as an unsigned value.

A simple example

readBin and writeBin

  1. Start with Two bytes, 0 and 7
  2. Do this Write and read the bytes
  3. Result 0, 7
Binary I/O preserves the zero byte as part of the data.

Syntax

R syntax
readBin(preset, "raw", n = 3)
Run these examples in R

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

Rscript --vanilla Lesson.R

Recover the brightest setting from a preset

A camera club stores three brightness levels in a compact binary preset. Read the saved bytes back and display the brightest setting as an unsigned number on the familiar 0–255 scale.

From the programdata <- readBin(preset, "raw", n = 3)
Result255
Lesson.R
run_example <- function() {
    base <- tempfile("lesson-")
    stopifnot(dir.create(base))
    on.exit(unlink(base, recursive = TRUE))
    preset <- file.path(base, "preset")
    writeBin(as.raw(c(0, 64, 255)), preset)
    data <- readBin(preset, "raw", n = 3)
    cat(as.integer(data[3]), "\n", sep = "")
}
run_example()
Output
255

The final byte has all eight bits set and represents 255.

Advertisements

Read a display preset

A museum sign saves three brightness levels as individual bytes. Read the unsigned byte at the indicated zero-based offset. Which stored sample is returned?

Given12 · 80 · 200 | offset 2
Worked result200

Read the first locker state

A desk stores two status values in a compact file. Read the unsigned byte at the indicated zero-based offset. Which stored sample is returned?

Given7 · 25 | offset 0
Worked result7

What to watch for

Text encoding can change byte values. Use binary I/O for this format.

Documentation for readBin and writeBin