Thread overview | ||||||
---|---|---|---|---|---|---|
|
November 29, 2006 Casting byte[] to int/long | ||||
---|---|---|---|---|
| ||||
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? ;) |
November 29, 2006 Re: Casting byte[] to int/long | ||||
---|---|---|---|---|
| ||||
Posted in reply to Henrik | 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
|
November 29, 2006 Re: Casting byte[] to int/long | ||||
---|---|---|---|---|
| ||||
Posted in reply to Bill Baxter | 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
|
November 29, 2006 Re: Casting byte[] to int/long | ||||
---|---|---|---|---|
| ||||
Posted in reply to Gregor Richards | Gregor Richards wrote:
>(Untested) That code will print 10 on a little-endian system, but will
print 0 on a big-endian system.
Shit, you are right. I would have forgotten about it :| std.system to the rescue!
|
Copyright © 1999-2021 by the D Language Foundation