Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert integer to string with C++ compatible function for Matlab Coder

I'm using Matlab Coder to convert some Matlab code to C++, however I'm having trouble converting intergers to strings.

int2str() is not supported for code generation, so I must find some other way to convert ints to strings. I've tried googling it, without success. Is this even possible?

like image 803
ein123 Avatar asked Jul 23 '15 07:07

ein123


2 Answers

This can be done manually (very painful, though)

function s = thePainfulInt2Str( n )
s = '';
is_pos = n > 0; % //save sign
n = abs(n); %// work with positive
while n > 0
    c = mod( n, 10 ); % get current character
    s = [uint8(c+'0'),s]; %// add the character
    n = ( n -  c ) / 10; %// "chop" it off and continue
end
if ~is_pos
    s = ['-',s]; %// add the sign
end
like image 62
Shai Avatar answered Sep 23 '22 03:09

Shai


sprintf is another very basic function, so it possibly works in C++ as well:

x = int64(1948)
str = sprintf('%i',x)

It is also the underlying function used by int2str.


According to this comprehensive list of supported functions, as pointed out by Matt in the comments, sprintf is not supported, which is surprising. However there is the undocumented helper function (therefore not in the list) sprintfc which seems to work and can be used equivalently:

str = sprintfc('%i',x)
like image 39
Robert Seifert Avatar answered Sep 24 '22 03:09

Robert Seifert