December 22, 2013 Re: ubytes to ulong problem | ||||
---|---|---|---|---|
| ||||
Posted in reply to Charles Hixson | On 12/22/2013 01:04 AM, Charles Hixson wrote: > Nice, but the block is longer than 8 bytes, so I should use a "for (i = > n; i < n + 8; i++)" rather than a foreach, and index off of i. Makes sense. That reminded me of the Phobos function that does exactly what you want. Have you considered std.bitmanip.read? Ali |
December 22, 2013 Re: ubytes to ulong problem | ||||
---|---|---|---|---|
| ||||
Posted in reply to Ali Çehreli | On Sunday, 22 December 2013 at 03:57:38 UTC, Ali Çehreli wrote:
> On 12/21/2013 05:44 PM, Charles Hixson wrote:
>> On 12/21/2013 03:52 PM, Ali Çehreli wrote:
>>> On 12/21/2013 03:13 PM, John Colvin wrote:
>>>
>>> > Ideally the compiler will optimise your version to be fast, but you may
>>> > find you get better performance by doing the bit manipulations
>>> eplicitly:
>>>
>>> Assuming that the program needs to support only big endian and little
>>> endian systems (i.e. excluding systems where no D compiler exists :)),
>>> the following is less wordy and should be equally fast:
>>>
>>> import std.bitmanip;
>>> import std.system;
>>>
>>> ulong ubytesToUlong(ubyte[] block, size_t n = 0)
>>> in
>>> {
>>> assert (n >= 0);
>>> assert (n + 8 <= block.length);
>>> }
>>> body
>>> {
>>> ulong value = *cast(ulong*)(block.ptr + n);
>>>
>>> if (std.system.endian == Endian.littleEndian) {
>>> return *cast(ulong*)(value.nativeToBigEndian.ptr);
>>>
>>> } else {
>>> return value;
>>> }
>>> }
>>>
>>> Ali
>>>
>>>
>> Will that work even when the alignment is to odd bytes? Because that's
>> the case I was really worried about. The ubyte array is a packed
>> mixture of types, some of which are isolated bytes.
>>
>
> No, it is not guaranteed to work unless the alignment is right.
It's just an unaligned load. If your target cpu architecture can't do unaligned loads then you're either using something very small or very old.
|
December 22, 2013 Re: ubytes to ulong problem | ||||
---|---|---|---|---|
| ||||
Posted in reply to Ali Çehreli | On 12/22/2013 02:22 AM, Ali Çehreli wrote: > On 12/22/2013 01:04 AM, Charles Hixson wrote: > > > Nice, but the block is longer than 8 bytes, so I should use a "for (i = > > n; i < n + 8; i++)" rather than a foreach, and index off of i. > > Makes sense. That reminded me of the Phobos function that does exactly what you want. Have you considered std.bitmanip.read? > > Ali > > No, thanks. That's precisely what I was looking for. -- Charles Hixson |
Copyright © 1999-2021 by the D Language Foundation