I have stumped myself on something that I thought should be relatively simple.
I have a character string that represents a binary string. For example:
x <- as.character(charToRaw("Hello World"))
I want to write x
to a file, but have been unable to invert the process of creating x
to get the original content. I had thought it would be as simple as
writeBin(as.raw(x),
con = "filename.txt")
But this doesn't produce a file with the text "Hello World". Nor does
writeBin(x,
con = "filename.txt")
When I try a direct inverse, I get an error
> x <- as.character(charToRaw("Hello World"))
> x
[1] "48" "65" "6c" "6c" "6f" "20" "57" "6f" "72" "6c" "64"
> rawToChar(as.raw(x))
Error in rawToChar(as.raw(x)) :
embedded nul in string: '0A\0\0\0\0249\0H\0@'
In addition: Warning messages:
1: In rawToChar(as.raw(x)) : NAs introduced by coercion
2: In rawToChar(as.raw(x)) :
out-of-range values treated as 0 in coercion to raw
Context
I know this is a weird way to approach the problem. I am under some weird constraints where I am saving data for a filled order to a SQL database as a JSON string. The user can include attachments with the request, and so I'm converting the raw vector to a character string to store in the JSON string. Where I'm having problems in reconstituting the character string to a raw vector that can be made into a copy of the original file.