convert ubyte[k..k + 1] to int

Roman D. Boiko rb at d-coding.com
Thu May 17 00:07:55 PDT 2012


On Thursday, 17 May 2012 at 04:16:10 UTC, Andrew Wiley wrote:
> On Wed, May 16, 2012 at 11:07 PM, H. S. Teoh 
> <hsteoh at quickfur.ath.cx> wrote:
>> Do unions suffer from this problem? Could this prevent 
>> alignment
>> problems:
>>
>>        short bytesToShort(ubyte[] b)
>>        in { assert(b.length==2); }
>>        body {
>>                union U {
>>                        short val;
>>                        ubyte[2] b;
>>                }
>>                U u;
>>
>>                u.b[] = b[];
>>                return u.val;
>>        }
>>
>> ?
>>
>>
> As I understand it, this should be fine because the compiler 
> will guarantee
> that the union is aligned to the maximum alignment required by 
> one of its
> members, which is the short. This is probably the safest 
> solution.

And what about the following code:

// This implementation is optimized for speed via swapping
endianness in-place
pure immutable(C)[] fixEndian(C, Endian blobEndian =
endian)(ubyte[] blob) if(is(CharTypeOf!C))
{
      import std.bitmanip, std.system;
      auto data = cast(C[]) blob;
      static if(blobEndian != endian)
      {
          static assert(!is(typeof(C) == char)); // UTF-8 doesn't
have endianness
          foreach(ref ch; data) ch = swapEndian(ch);
      }
      return cast(immutable) data;
}



More information about the Digitalmars-d-learn mailing list