Tuszynski, Jaroslaw W.
2005-Mar-23 20:09 UTC
[R] Looking for function for Double to raw to double conversions
Hello,
I am trying to implement function for reading/writing some XML file format.
One feature of that XML format is that a lot of binary data is stored in
Base64 format, and since R's XML package does not seem to support it, I just
wrote my own converter from "raw" format to Base64, and back. However
one
place I have problems with is conversion from vector of doubles to vector of
"raw"s.
I was expecting equivalent of C casting operation, like:
double *doubleVec;
unsigned char* rawVec;
rawVec = (unsigned char*) doubleVec;
Or if compiler complains:
rawVec = (unsigned char*) ((void*) doubleVec);
Unfortunately I can not find equivalent function in R. Simple minded:
doubleVec = (1:4)*pi
rawVec = as.raw(doubleVec)
as.double(rawVec)
Does not seem to work (output: 3 6 9 12, instead of: 3.141593 6.283185
9.424778 12.566371) .
The only way I figured out how to do it is by using:
raw2double = function(x)
{
writeBin(as.raw(x), "temp.bin")
return( readBin("temp.bin", "double", n=length(x)%/%8) )
}
double2raw = function(x)
{
writeBin(as.double(x), "temp.bin")
return( readBin("temp.bin", "raw", n=length(x)*8) )
}
Than:
rawVec = double2raw(doubleVec)
raw2double(rawVec)
Gives correct results.
Is there any other way that does not use temporary files to do this simple
casting, that does not involve writing my own C code (which I am trying to
avoid).
Jarek
=====================================\====
Jarek Tuszynski, PhD. o / \
Science Applications International Corporation <\__,|
(703) 676-4192 "> \
Jaroslaw.W.Tuszynski@saic.com ` \
[[alternative HTML version deleted]]
