Można również zadzwonić runtime C sprintf
lub snprintf
korzystając coder.ceval
. Ma to tę zaletę, że ułatwia również wprowadzanie wspomagających sygnałów zmiennoprzecinkowych. Możesz również zmienić formatowanie według potrzeb, modyfikując ciąg formatu.
Zakładając, że kompilator zapewnia snprintf
jeden mógłby użyć:
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
Zauważ, że będziesz prawdopodobnie musiał dostosować ciąg formatu w celu dopasowania do sprzętu, na którym używasz ponieważ zakłada, że long long
jest dostępny i mapuje do niej 64-bitowe liczby całkowite.
Czy obsługiwany jest 'num2str'? Jest to najbardziej ogólna funkcja tego typu. – buzjwa
num2str nie jest niestety nieobsługiwany. – ein123