digitalmars.D - Casting byte[] to int/long
- Henrik (10/10) Nov 29 2006 Hello!
- Bill Baxter (5/20) Nov 29 2006 You need something like:
- Gregor Richards (12/39) Nov 29 2006 You probably know this, but be very careful while doing this, endianness...
- Henrik (4/5) Nov 29 2006 print 0 on a big-endian system.
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? ;)
Nov 29 2006
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
Nov 29 2006
Bill Baxter wrote:Henrik wrote: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 RichardsHello! 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
Nov 29 2006
Gregor Richards wrote:(Untested) That code will print 10 on a little-endian system, but willprint 0 on a big-endian system. Shit, you are right. I would have forgotten about it :| std.system to the rescue!
Nov 29 2006