Casting byte[] to int/long
Gregor Richards
Richards at codu.org
Wed Nov 29 10:14:19 PST 2006
Bill Baxter wrote:
> Henrik wrote:
>
>> Hello!
>>
>> If I have a dynamic array of bytes, say
>>
>> byte[] a; a = [1,2,3,4];
>>
>> Is it possible to somehow cast a number of these bytes into an int or
>> a long,
>> like so;
>>
>> int b = cast(int)a[0..2];
>> long c = cast(long)a;
>>
>> or something? The goal is to convert 2 * 8 bit into 1 * 16 bit or 4 *
>> 8 bit
>> into 1 * 64 bit. 1) Is it possible? 2) Is it possible without
>> confusing the
>> GC? 3) How? ;)
>
>
> You need something like:
> int b = *cast(int*)&a[0];
> long c = *cast(long*)a.ptr;
>
> --bb
You probably know this, but be very careful while doing this, endianness
makes all the difference:
int main()
{
long a = 10;
int *b = cast(int *) &a;
writefln("%d", *b);
}
(Untested) That code will print 10 on a little-endian system, but will
print 0 on a big-endian system.
- Gregor Richards
More information about the Digitalmars-d
mailing list