How to convert a RawArray of bytes to ByteArray?
At present there is no way to do this from top level, since there is no interface to the internal function that converts a rank-1 RawArray
of bytes into a ByteArray
.
However, as already pointed out, it's possible to take advantage of LibraryLink which will do a conversion given an MRawArray
on the C side and a "ByteArray"
return type, for example
Needs["CCompilerDriver`"]
src = "
#include \"WolframLibrary.h\"
#include \"WolframRawArrayLibrary.h\"
DLLEXPORT mint WolframLibrary_getVersion() {
return WolframLibraryVersion;
}
DLLEXPORT int WolframLibrary_initialize( WolframLibraryData libData) {
return 0;
}
DLLEXPORT void WolframLibrary_uninitialize( WolframLibraryData libData) {
return;
}
DLLEXPORT int mrawarray_to_bytearray( WolframLibraryData libData,
mint Argc, MArgument *Args, MArgument Res) {
WolframRawArrayLibrary_Functions rawFuns = libData->rawarrayLibraryFunctions;
MRawArray ra;
mint rank;
rawarray_t type;
if (Argc != 1) return LIBRARY_FUNCTION_ERROR;
ra = MArgument_getMRawArray(Args[0]);
type = rawFuns->MRawArray_getType(ra);
rank = rawFuns->MRawArray_getRank(ra);
if (rank == 1 && type == MRawArray_Type_Ubit8) {
MArgument_setMRawArray(Res, ra);
return LIBRARY_NO_ERROR;
}
return LIBRARY_FUNCTION_ERROR;
}";
lib = CreateLibrary[src, "toByteArray"];
toByteArray = LibraryFunctionLoad[lib,
"mrawarray_to_bytearray", {"RawArray"}, "ByteArray"];
toByteArray[RawArray["Byte", {1, 2, 3, 4}]]
(* ByteArray["AQIDBA=="] *)
The new in M12 function NumericArray
is essentially the documented version of the undocumented RawArray
. The conversions between ByteArray
and NumericArray
are straightforward:
ba = ByteArray[{1,2,3,4}];
ba //InputForm
ByteArray["AQIDBA=="]
Conversion to a NumericArray
:
na = NumericArray[ba, "Byte"];
na //InputForm
NumericArray[{1, 2, 3, 4}, "UnsignedInteger8"]
Conversion back to a ByteArray
:
ba === ByteArray @ na
True
Note that your RawArray
syntax is still supported, but it now constructs a NumericArray
object instead:
RawArray["Byte", ba] //InputForm
NumericArray[{1, 2, 3, 4}, "UnsignedInteger8"]