string to char[4] FourCC conversion

realhet real_het at hotmail.com
Fri May 26 12:19:20 UTC 2023


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;
}
```

I tried to use staticArray!(char, 4), on s.byChar, but failed.

I think I could do this using 
cast(char[4])(s.take(4).enumerate.map!"cast(uint)(a.value)<<<(a.index*8)".sum), but that seems no so effective. But at least that works in CT.

I hope there is a more clever way in the std library I couldn't 
imagine at the moment...

```
//I also tried an arithmetic version, but it's impossible to 
convert to char[4] except with using pointer casts...
uint fourCC(string s)
{ return s.take(4).enumerate.map!(a => a.value << 
cast(uint)a.index*8).sum; }
```


More information about the Digitalmars-d-learn mailing list