Title here
Summary here
R provides support for base64 encoding/decoding through the base64enc package.
# Install and load the base64enc package
install.packages("base64enc")
library(base64enc)
# Here's the string we'll encode/decode
data <- "abc123!?$*&()'-=@~"
# Encoding using standard base64
sEnc <- base64encode(charToRaw(data))
cat("Standard encoded:", sEnc, "\n")
# Decoding
sDec <- rawToChar(base64decode(sEnc))
cat("Decoded:", sDec, "\n\n")
# Encoding using URL-safe base64
uEnc <- base64encode(charToRaw(data), urlsafe = TRUE)
cat("URL-safe encoded:", uEnc, "\n")
# Decoding URL-safe
uDec <- rawToChar(base64decode(uEnc))
cat("Decoded:", uDec, "\n")In this R script:
We first install and load the base64enc package, which provides base64 encoding and decoding functions.
We define our input string data.
For standard base64 encoding:
base64encode() function to encode the string.charToRaw().base64decode() and then convert the raw bytes back to a character string with rawToChar().For URL-safe base64 encoding:
base64encode() function, but with the urlsafe = TRUE parameter.When you run this script, you should see output similar to this:
Standard encoded: YWJjMTIzIT8kKiYoKSctPUB+
Decoded: abc123!?$*&()'-=@~
URL-safe encoded: YWJjMTIzIT8kKiYoKSctPUB-
Decoded: abc123!?$*&()'-=@~Note that in R, the URL-safe encoding replaces + with - and / with _, which is why you see a - at the end of the URL-safe encoded string instead of a +.
R’s base64 functions handle the conversion between different data types (character strings and raw bytes) automatically, making the process straightforward.