string to char[4] FourCC conversion

Steven Schveighoffer schveiguy at gmail.com
Fri May 26 13:18:15 UTC 2023


On 5/26/23 8:19 AM, realhet wrote:
> Hello,
> 
> Is there a way to do it nicer/better/faster/simpler?
> 
> ```
> char[4] fourC(string s)
> {
>      uint res;//Zero initialized, not 0xff initialized.
>      auto     cnt = min(s.length, 4),
>          p = cast(char[4]*)(&res);
>      (*p)[0..cnt] = s[0..cnt];
>      return *p;
> }
> ```

This worked for me:

```d
char[4] fourC(string s)
{
     if(s.length >= 4)
         return s[0 .. 4];
     char[4] res = 0;
     res[0 .. s.length] = s;
     return res;
}
```

Supporting returning as a 4-char array even when the input has less than 
4 makes it tricky. But not so bad.

-Steve


More information about the Digitalmars-d-learn mailing list