I have data created/modified in r in a large vector converted to integer. I need to write the data as a binary file which will be read by another app, ImageJ. I was unable to find an R function to do this so I tried Rcpp. The written file size is as expected but the individual data are not. My test example is below.
RStudio 2021.09.0 Build 351
R version 4.1.3 (2022-03-10) -- "One Push-Up"
MacOS Monterey ver 12.4
Rcpp function
r <- 1:20
typeof(r)
[1] "integer"
#include <Rcpp.h>
#include <stdlib.h>
#include <string>
#include <stdio.h>
using namespace Rcpp;
// [[Rcpp::export]]
int cpp_saveAsBin (const IntegerVector & imgData, const std::string fname) {
FILE *outP = fopen(fname.c_str(), "wb");
if (outP == NULL) Rcpp::stop("Cannot open file", fname);
int res = fwrite(imgData, sizeof(int), imgData.size(), outP);
fclose(outP);
return (res);
}
Testing
> r <- 1:20
> typeof(r)
[1] "integer"
> cpp_saveAsBin(as.integer(r), "test.rawP")
[1] 20
Checking with xxd (trimmed to shorten the line.
xxd test.rawP
00000000: 8d00 0001 ffff 0000 e072 8259 0100 0000
00000010: 78a9 7058 0100 0000 0885 115b 0100 0000
00000020: 3880 c05f 0100 0000 0831 4b3c 0100 0000
00000030: c000 6f02 0060 0000 0200 0000 0100 0000
00000040: e072 8259 0100 0000 b04f 3938 0100 0000
The values are not binary representations from 1 through 20. What's going on? Is there a better method?
TIA