Cast
Details
- Cast is only available in compiled code.
- Possible values of method in Cast[val,type,method] include:
-
"BitCast" reinterprets the bits representing val as having the type type "CCast" emulates the behavior of casting in C "ConversionCast" converts val to the type type - The default casting method is "ConversionCast".
- Cast[val,type,"BitCast"] behaves as though val is written to memory and read back as type.
The input type to a bitcast must have the same memory size as the output type. - Cast[val,type,"CCast"] only supports numeric types.
- Cast[val,type,"ConversionCast"] can fail with an error.
Examples
open all close allBasic Examples (2)
Cast an "Integer64" to a "Real64" in a compiled function:
cf = FunctionCompile[Function[Typed[arg, "Integer64"],
Cast[arg, "Real64"]
]]cf[2]Cast an expression to a packed array, suitable for use with other compiled functions:
cf = FunctionCompile[Function[Typed[arg, "InertExpression"],
Reverse[Cast[arg, "PackedArray"::["Real64", 1]]]
]]cf[{1, 2, 3}]Some expressions cannot be converted into packed arrays:
cf["test"]Scope (2)
Bitcast a pointer to an integer:
cf = FunctionCompile[Function[{},
Module[{ptr, res},
ptr = LibraryFunction["malloc"][Typed[1, "UnsignedInteger64"]];
res = Cast[ptr, "UnsignedInteger64", "BitCast"];
LibraryFunction["free"][ptr];
res
]
]]cf[]Cast from a larger type to a smaller one with a C-style cast:
cf = FunctionCompile[Function[Typed[arg, "Integer64"], Cast[arg, "Integer32", "CCast"]]]cf[100]As in C, the "CCast" method does not check for numerical overflows:
cf[2 ^ 32]Possible Issues (1)
The default casting method "ConversionCast" does not currently support casting from larger types to smaller types:
cf = FunctionCompile[Function[Typed[arg, "Integer64"], Cast[arg, "Integer32"]]]cf = FunctionCompile[Function[Typed[arg, "Integer64"], Cast[arg, "Integer32", "CCast"]]]However, "CCast" does not check for numerical overflows:
cf[2 ^ 32]Related Guides
History
Text
Wolfram Research (2022), Cast, Wolfram Language function, https://reference.wolfram.com/language/ref/Cast.html.
CMS
Wolfram Language. 2022. "Cast." Wolfram Language & System Documentation Center. Wolfram Research. https://reference.wolfram.com/language/ref/Cast.html.
APA
Wolfram Language. (2022). Cast. Wolfram Language & System Documentation Center. Retrieved from https://reference.wolfram.com/language/ref/Cast.html
BibTeX
@misc{reference.wolfram_2026_cast, author="Wolfram Research", title="{Cast}", year="2022", howpublished="\url{https://reference.wolfram.com/language/ref/Cast.html}", note=[Accessed: 13-June-2026]}
BibLaTeX
@online{reference.wolfram_2026_cast, organization={Wolfram Research}, title={Cast}, year={2022}, url={https://reference.wolfram.com/language/ref/Cast.html}, note=[Accessed: 13-June-2026]}