You can also invoke C runtime sprintf or snprintf using coder.ceval . It also makes it easy to support floating point helper functions. You can also change the formatting as desired by changing the format string.
Suppose your compiler provides snprintf , which you can use:
function s = cint2str(x) %#codegen if coder.target('MATLAB') s = int2str(x); else coder.cinclude('<stdio.h>'); assert(isfloat(x) || isinteger(x), 'x must be a float or an integer'); assert(x == floor(x) && isfinite(x), 'x must be a finite integer value'); if isinteger(x) switch class(x) % Set up for Win64, change to match your target case {'int8','int16','int32'} fmt = '%d'; case 'int64' fmt = '%lld'; case {'uint8','uint16','uint32'} fmt = '%u'; otherwise fmt = '%llu'; end else fmt = '%.0f'; end % NULL-terminate for C cfmt = [fmt, 0]; % Set up external C types nt = coder.opaque('int','0'); szt = coder.opaque('size_t','0'); NULL = coder.opaque('char*','NULL'); % Query length nt = coder.ceval('snprintf',NULL,szt,coder.rref(cfmt),x); n = cast(nt,'int32'); ns = n+1; % +1 for trailing null % Allocate and format s = coder.nullcopy(blanks(ns)); nt = coder.ceval('snprintf',coder.ref(s),cast(ns,'like',szt),coder.rref(cfmt),x); assert(cast(nt,'int32') == n, 'Failed to format string'); end
Note that you may need to tweak the format string to match the hardware you are running on, as this assumes that long long is available and matches 64-bit integers with it.
source share