Search code examples
typesd

Assign int value to char


While learning C++ and D I am trying to compare the ease of use by testing some code in both languages.

So, in C++ I have something like this (not showing complete C++ code it's just for the demo):

char src[] = "some10char";
char des[];

for (int i=0; i<1000; i++)
{
    src[9] = '0' + i % (126 - '0');
    des = src;
}

In the 'pseudo' above, first line in the body of for loop not only assigns the int value, but also tries to avoid unprintable values.

How could I do same in D?

So far I have managed to cast int to char and I don't know if I have made it correctly:

char[] src = "some10char".dup;
char[] dst;

for (int i=0; i<1000; i++)
{   
    if (i<15) 
        src[src.length-1] = cast(char)(i+15);
    else
        src[src.length-1] = cast(char)(i);

    dst = src.dup // testing also dst = src;
}

Solution

  • You can add and substract from a character litteral in D, just as in your c++ sample, eg:

    import std.stdio;
    
    char[] str;
    
    void main(string[] args)
    {
        for(int i=0; i<1000; i++)
        {
            str ~= cast(char)( i % (0x7F - '0') + '0') ;
        }
        writeln(str);
    }
    

    to print only ascii characters over 0 and less than 0x7F. The character is implicitly converted to an int and the final operation on i (which itself gives an int) is then explicitely casted to a char (so modulo/mask by 0xFF).