digitalmars.D - Casting byte[] to int/long
- Henrik <zodiachus gmail.com> Nov 29 2006
- Bill Baxter <wbaxter gmail.com> Nov 29 2006
- Gregor Richards <Richards codu.org> Nov 29 2006
- Henrik <zodiachus gmail.com> Nov 29 2006
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: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
Nov 29 2006
Gregor Richards wrote:(Untested) That code will print 10 on a little-endian system, but will
Shit, you are right. I would have forgotten about it :| std.system to the rescue!
Nov 29 2006








Henrik <zodiachus gmail.com>