5

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.

Benjamin
  • 16,897
  • 6
  • 45
  • 65

1 Answers1

6

This will get you the inverse operation:

x <- as.character(charToRaw("Hello World"))
rawToChar(as.raw(as.hexmode(x)))
## [1] "Hello World"
Josh O'Brien
  • 159,210
  • 26
  • 366
  • 455
  • [See here too](http://stackoverflow.com/questions/29928091/unserialize-objects-from-in-memory-ascii-instead-of-from-a-file-connection/29928738#29928738) for a similar answer to a user facing a similar challenge. – Josh O'Brien Feb 29 '16 at 16:20
  • I had a feeling it would be something really simple. Thanks. – Benjamin Feb 29 '16 at 16:23
  • Could you please check my question also http://stackoverflow.com/questions/36244709/database-as-it-is-raw-content –  Mar 27 '16 at 07:12