bytes into integer, need help
Steven Schveighoffer
schveiguy at yahoo.com
Thu Nov 6 07:22:36 PST 2008
"James" wrote
> im having problem in code below, while making my own file handler. the
> data stored in buffer, so i can recall portion of data in diff format and
> length like int,short,etc. but im stuck with function getb() below. any
> suggestion? thks.
>
> struct T_FILE_RAM {
> ubyte[] buffer;
> int offset;
>
> void getb(void* buf, int size) {
> buf=&b[offset..offset+size]; //<-- prob here
> }
>
> void read(out uint x) { getb(&x, x.sizeof); }
> void read(out ushort x) { getb(&x, x.sizeof); }
>
> }
I think you meant this?
buf[0..size] = buffer[offset..offset+size];
And also, you need to increment offset, no?
offset += size.
I'd also recommend using a template:
void getb(T)(ref T t)
{
auto size = t.sizeof;
auto buf = (cast(ubyte *)&t)[0..size];
buf[] = buffer[offset..offset+size];
offset += size;
}
Now you don't need to implement each type, and you can call like this:
int x;
ushort y;
getb(x); // reads 4 bytes
getb(y); // reads 2 bytes
-Steve
More information about the Digitalmars-d-learn
mailing list