({{, (RefLink[BinarySerialize, paclet:ref/BinarySerialize])[expr] 
gives a binary representation of any expression expr as a (RefLink[ByteArray, paclet:ref/ByteArray]) object.}})

OpenersNotesSection(Spacer1)Details and Options

(RefLink[BinarySerialize, paclet:ref/BinarySerialize]) has the following options:

Possible settings for (RefLink[PerformanceGoal, paclet:ref/PerformanceGoal]) include:

Possible settings for (RefLink[Method, paclet:ref/Method]) include:

Possible forms for the (Subscript[typespec, i]) include:

Possible settings for "PackedArrayIntegerType" include (StringTypeLink["Integer8", paclet:ref/format/Integer8]), (StringTypeLink["Integer16", paclet:ref/format/Integer16]), (StringTypeLink["Integer32", paclet:ref/format/Integer32]) and (StringTypeLink["Integer64", paclet:ref/format/Integer64]) (64-bit systems only).

Possible settings for "PackedArrayRealType" include (StringTypeLink["Real32", paclet:ref/format/Real32]) and (StringTypeLink["Real64", paclet:ref/format/Real64]).

Possible settings for "PackedArrayComplexType" include (StringTypeLink["Complex64", paclet:ref/format/Complex64]) and (StringTypeLink["Complex128", paclet:ref/format/Complex128]).

The default for the (Subscript[enc, i]) encoding specifications is (RefLink[Automatic, paclet:ref/Automatic]), in which case (RefLink[BinarySerialize, paclet:ref/BinarySerialize]) will use a type that fits the data it is given.

(RefLink[BinarySerialize, paclet:ref/BinarySerialize]) uses the (StringTypeLink[WXF, paclet:ref/format/WXF]) format.

(RefLink[BinaryDeserialize, paclet:ref/BinaryDeserialize]) is the inverse of (RefLink[BinarySerialize, paclet:ref/BinarySerialize]).

OpenersPrimaryExamplesSection(Spacer1)Examples  (20)

OpenersExampleSection0(Spacer1)Basic Examples  (2)

Serialize an expression:

BinarySerialize[{1,2,3}]

Serialize a graphic:

BinarySerialize[Plot[Sin[x], {x,0,Pi}]]

Convert the serialized form back to an expression:

BinaryDeserialize[%]

OpenersExampleSection1(Spacer1)Scope  (7)

Apply (RefLink[BinarySerialize, paclet:ref/BinarySerialize]) to symbolic expressions:

BinarySerialize[f[Sin[g[x]]]]

Serialize an image:

BinarySerialize[]

Note that the size of the serialized form roughly equals the byte count of the expression:

ByteCount[]

(RefLink[BinarySerialize, paclet:ref/BinarySerialize]) efficiently stores machine integers:

BinarySerialize[2^7-1]

BinarySerialize[2^15-1]

BinarySerialize[2^31-1]

(RefLink[BinarySerialize, paclet:ref/BinarySerialize]) efficiently stores machine reals:

BinarySerialize[N[1234/5678]]

Compare with an arbitrary-precision real:

BinarySerialize[N[1234/5678,16]]

(RefLink[BinarySerialize, paclet:ref/BinarySerialize]) efficiently stores strings:

str=FromCharacterCode[RandomInteger[{0,2^15},1000]];

ByteCount[str]

BinarySerialize[str]

(RefLink[BinarySerialize, paclet:ref/BinarySerialize]) supports (RefLink[ByteArray, paclet:ref/ByteArray]):

BinarySerialize[ByteArray[RandomInteger[255,1000]]]

(RefLink[BinarySerialize, paclet:ref/BinarySerialize]) supports packed arrays:

ints=RandomInteger[2^($SystemWordLength-2),1000];
reals=RandomReal[1,1000];
complexes= RandomComplex[{0,1+I},1000];

ByteCount/@{ints,reals,complexes}

BinarySerialize/@{ints,reals,complexes}

OpenersExampleSection2(Spacer1)Options  (4)

OpenersExampleSubsection0(Spacer1)Method  (3)

Create a packed array of integer values:

integers = ConstantArray[2^14,3];

By default, (RefLink[BinarySerialize, paclet:ref/BinarySerialize]) uses the smallest integer type that fits the data:

BinarySerialize[integers]

Serialize the packed array using a bigger integer type:

BinarySerialize[integers,Method->"PackedArrayIntegerType"->"Integer32"]

Create a packed array of real values:

reals=RandomReal[1,3]

Serialize the array:

real64=BinarySerialize[reals]

Serialize the array using machine floats, trading precision for a smaller output:

real32=BinarySerialize[reals,Method->"PackedArrayRealType"->"Real32"]

Create a packed array of complex values:

complexes = RandomComplex[1+I,3]

Serialize the array:

BinarySerialize[complexes]

Serialize the array using lower precision:

BinarySerialize[complexes,Method->{"PackedArrayComplexType"->"Complex64"}]

OpenersExampleSubsection1(Spacer1)PerformanceGoal  (1)

Serialize a (RefLink[Dataset, paclet:ref/Dataset]):

data=ExampleData[{"NetworkGraph","AstrophysicsCollaborations"}];

uncompressed=BinarySerialize[data]

Serialize the same (RefLink[Dataset, paclet:ref/Dataset]) with (RefLink[PerformanceGoal, paclet:ref/PerformanceGoal]) set to "Size":

compressed=BinarySerialize[data, PerformanceGoal->"Size"]

Both forms represent the same expression:

BinaryDeserialize[uncompressed]==BinaryDeserialize[compressed]

OpenersExampleSection3(Spacer1)Applications  (1)

Serialize a trained neural network:

bin=BinarySerialize[ NetTrain[NetGraph[{1,3,3,1},{1->2->3->4},"Input"->"Scalar","Output"->"Scalar"],{.1->.07,.25->.24,.3->.32,.5->.5},MaxTrainingRounds->1000]
]

Create a new file:

file=CreateFile[];

Open an output binary stream:

ow=OpenWrite[file, BinaryFormat->True]

Write the serialized expression to the file:

BinaryWrite[ow,bin]

Close[ow];

Read the data from the file:

nettrained=BinaryDeserialize[ByteArray[BinaryReadList[file, "Byte"]]]

Plot the prediction of the net as a function of the input:

Plot[nettrained[x], {x,0,5}]

OpenersExampleSection4(Spacer1)Properties & Relations  (4)

Using (RefLink[PerformanceGoal, paclet:ref/PerformanceGoal])->"Speed" is faster but produces larger outputs:

data=Range[10^6];

BinarySerialize[data,PerformanceGoal->"Speed"]//AbsoluteTiming

Using (RefLink[PerformanceGoal, paclet:ref/PerformanceGoal])->"Size" is slower but produces smaller outputs:

BinarySerialize[data,PerformanceGoal->"Size"]//AbsoluteTiming

(RefLink[BinarySerialize, paclet:ref/BinarySerialize]) encodes strings as UTF-8:

bytes=BinarySerialize["→ hello there ←"]

ByteArrayToString[bytes, "UTF-8"]

(RefLink[BinaryDeserialize, paclet:ref/BinaryDeserialize]) is the inverse of (RefLink[BinarySerialize, paclet:ref/BinarySerialize]):

BinaryDeserialize[BinarySerialize[x]]===x

(RefLink[DumpSave, paclet:ref/DumpSave]) stores definitions attached to a symbol in a file:

f[x_]:= x^2

mx=FileNameJoin[{$TemporaryDirectory,"f.mx"}];
DumpSave[mx,f];

Using (RefLink[Get, paclet:ref/Get]) will return (RefLink[Null, paclet:ref/Null]) but restore the value of f:

Clear[f];
restored=Get[mx];
DeleteFile[mx];
{restored,f[x]}

(RefLink[BinarySerialize, paclet:ref/BinarySerialize]) only stores the input expression, which can be restored by (RefLink[BinaryDeserialize, paclet:ref/BinaryDeserialize]):

BinarySerialize[f];
Clear[f];
restored=BinaryDeserialize[%%];
{restored,f[x]}

OpenersExampleSection5(Spacer1)Possible Issues  (2)

From small expressions, (RefLink[PerformanceGoal, paclet:ref/PerformanceGoal])->(RefLink["Size", paclet:ref/menuitem/Size]) may not produce smaller outputs:

BinarySerialize[{1,2,3}, PerformanceGoal->"Size"]

BinarySerialize[{1,2,3}]

The (RefLink[Method, paclet:ref/Method]) parameter "PackedArrayIntegerType" must be chosen consistently with the data:

BinarySerialize[ConstantArray[2^17,3], Method->{"PackedArrayIntegerType"->"Integer16"}]

These values require 32-bit integers:

BinarySerialize[ConstantArray[2^17,3],Method->{"PackedArrayIntegerType"->"Integer32"}]

A setting of (RefLink[Automatic, paclet:ref/Automatic]) will always use a size that fits the data:

BinarySerialize[ConstantArray[2^17,3],Method->{"PackedArrayIntegerType"->Automatic}]

({{DocumentationFooterIconsRelatedFunction.png, ({{See Also}, {(RefLink[BinaryDeserialize, paclet:ref/BinaryDeserialize])  ▪  (RefLink[DumpSave, paclet:ref/DumpSave])  ▪  (RefLink[Compress, paclet:ref/Compress])  ▪  (RefLink[ExportByteArray, paclet:ref/ExportByteArray])  ▪  (RefLink[ByteArray, paclet:ref/ByteArray])  ▪  (RefLink[BaseEncode, paclet:ref/BaseEncode])  ▪  (RefLink[ByteArrayToString, paclet:ref/ByteArrayToString])  ▪  (RefLink[StringToByteArray, paclet:ref/StringToByteArray])  ▪  (RefLink[Export, paclet:ref/Export])  ▪  (RefLink[FullForm, paclet:ref/FullForm])  ▪  (RefLink[InputForm, paclet:ref/InputForm])  ▪  (RefLink[BinaryWrite, paclet:ref/BinaryWrite])}})}})

({{DocumentationFooterIconsRelatedTutorial.png, ({{Tutorials}, {▪(RefLinkPlain[WXF Format Description, paclet:tutorial/WXFFormatDescription])}})}})

({{DocumentationFooterIconsRelatedGuide.png, ({{Related Guides}, {▪(RefLinkPlain[Wolfram Language Expressions in Files, paclet:guide/WolframLanguageExpressionsInFiles])}, {▪(RefLinkPlain[Binary Data, paclet:guide/BinaryData])}, {▪(RefLinkPlain[Importing & Exporting Database Formats, paclet:guide/ImportingAndExportingDatabaseFormats])}, {▪(RefLinkPlain[Importing and Exporting, paclet:guide/ImportingAndExporting])}, {▪(RefLinkPlain[Memory Measurement & Optimization, paclet:guide/MemoryMeasurementAndOptimization])}, {▪(RefLinkPlain[Files, paclet:guide/Files])}, {▪(RefLinkPlain[Wolfram Language File Formats, paclet:guide/WolframLanguageFileFormats])}})}})