base (version 3.4.1)

rawConversion: Convert to or from Raw Vectors


Conversion and manipulation of objects of type "raw".


rawToChar(x, multiple = FALSE)

rawShift(x, n)

rawToBits(x) intToBits(x) packBits(x, type = c("raw", "integer"))



object to be converted or shifted.


logical: should the conversion be to a single character string or multiple individual characters?


the number of bits to shift. Positive numbers shift right and negative numbers shift left: allowed values are -8 ... 8.


the result type, partially matched.


charToRaw converts a length-one character string to raw bytes. It does so without taking into account any declared encoding (see Encoding).

rawToChar converts raw bytes either to a single character string or a character vector of single bytes (with "" for 0). (Note that a single character string could contain embedded nuls; only trailing nulls are allowed and will be removed.) In either case it is possible to create a result which is invalid in a multibyte locale, using UTF-8. Long vectors are allowed if multiple is true.

rawShift(x, n) shift the bits in x by n positions to the right, see the argument n, above.

rawToBits returns a raw vector of 8 times the length of a raw vector with entries 0 or 1. intToBits returns a raw vector of 32 times the length of an integer vector with entries 0 or 1. (Non-integral numeric values are truncated to integers.) In both cases the unpacking is least-significant bit first.

packBits packs its input (using only the lowest bit for raw or integer vectors) least-significant bit first to a raw or integer vector.


packBits accepts raw, integer or logical inputs, the last two without any NAs.

Note that ‘bytes’ are not necessarily the same as characters, UTF-8 locales.


Run this code
x <- "A test string"
(y <- charToRaw(x))
is.vector(y) # TRUE

rawToChar(y, multiple = TRUE)
(xx <- c(y,  charToRaw("&"), charToRaw("more")))

rawShift(y, 1)
rawShift(y, -2)


showBits <- function(r) stats::symnum(as.logical(rawToBits(r)))

z <- as.raw(5)
z ; showBits(z)
showBits(rawShift(z, 1)) # shift to right
showBits(rawShift(z, 2))
showBits(rawShift(z, -1)) # shift to left
showBits(rawShift(z, -2)) # ..
showBits(rawShift(z, -3)) # shifted off entirely

Run the code above in your browser using DataCamp Workspace