data mapping, more elegant solution?
Regan Heath
regan at netmail.co.nz
Thu Dec 13 06:47:03 PST 2007
Regan Heath wrote:
> mandel wrote:
>> On Thu, 13 Dec 2007 13:35:35 +0000, Regan Heath wrote:
>>> Use a union?
>>>
>>> union thing
>>> {
>>> ubyte[8] ub;
>>> uint ui;
>>> }
>>>
>>> void main()
>>> {
>>> thing a;
>>> a.ui = 42;
>>> }
>>>
>> This way I can't insert data at arbitrary places, e.g. array[4..8].
>> I also would have to cast thing to ubyte[8] when I pass it to functions.
>> It's also hackish. :P
>
> If you want to insert a 'short' into it then add an array of shorts too:
>
> union thing
> {
> ubyte[8] ub;
> ushort[2] us;
> uint ui;
> }
>
> thing a;
>
> a.us[0] = 1; //ub[0..4]
> a.us[1] = 2; //ub[4..8]
>
> It's less hackish, and cleaner/clearer than using casts.
I must have been half asleep when I posted that. I got the sizes
confused. You have 64 bits of data, so your complete union would look
something like:
union thing
{
ubyte[8] ub;
ushort[4] us;
uint[2] ui;
ulong ul;
}
I got the assignments correct though, a.us[0] assigns to a.ub[0..4] and
so on. You may need to deal with big/little endian issues, not sure.
If you really hate the union and would rather use a cast I suggest:
ubyte[8] array;
(cast(uint*)&array)[0] = 1; //array[0..4]
(cast(uint*)&array)[1] = 2; //array[4..8]
I think that works, I don't have a compiler here to test it, it might
need to be:
(cast(uint*)&array)[0..2][0] = 1; //array[0..4]
(cast(uint*)&array)[0..2][1] = 2; //array[4..8]
The above creates a temporary dynamic array of type uint with length ==
2, which is less efficient than the union .. and more typing too.
Regan
More information about the Digitalmars-d-learn
mailing list