5

I'm trying to write an HTTP POST request, but I need to get my data into binary format first. This is probably an easy question, but I find R connections really confusing, and I've been having trouble finding a good resource that explains them in a way I understand.

So as an example, say I want to encode an integer (8 byte) and then a numeric (4 byte). Here is the code I've tried:

myint <- as.integer(1339700942)
mydouble <- 1.2
obj <- file(open='w+b') #I've tried textConnection too, but no good
w.int <- writeBin(myint, obj, size=8, endian='big')
w.double <- writeBin(mydouble, obj, size=4, endian='big')

This allowed me to open the connection, but all it wrote was NULL. What is the correct way to use connections and writeBin in a situation like this?

7
  • Thanks Joshua! My mistake with the variable names. Commented Jul 20, 2012 at 19:26
  • 1
    According to ?writeBin it returns NULL unless the con argument is a raw vector, which it is not in your example. It would help if you could give more background on your actual problem. Commented Jul 20, 2012 at 19:28
  • The example is very close to my actual problem. I want to post XDR data onto a website, and the format will be a repeating sequence of 8-byte ints and 4-byte floats. Commented Jul 20, 2012 at 19:32
  • should I assign 'obj <- raw(0)' instead of opening a connection...? Commented Jul 20, 2012 at 19:33
  • 2
    I'm really glad you figured out your problem! Would you please write an answer summarizing what worked for you and (after the mandatory waiting period) accept it? That way it's more likely that other people will benefit from what you learned. (As an added incentive, I will check back and up vote your answer...) Commented Jul 21, 2012 at 3:42

1 Answer 1

4

The object 'obj' is not actually necessary. If writeBin is writing to an R object rather than a file outside of R, the last three lines can be replaced by:

w.int <- writeBin(myint, raw(0), size=8, endian='big')
w.double <- writeBin(mydouble, raw(0), size=4, endian='big')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.