bytes into integer, need help
Denis Koroskin
2korden at gmail.com
Thu Nov 6 07:36:51 PST 2008
On Thu, 06 Nov 2008 18:22:36 +0300, Steven Schveighoffer
<schveiguy at yahoo.com> wrote:
> "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
>
>
Good solution also cares about endianess.
Also take a look at tango.io.protocol - it should cover all your needs.
More information about the Digitalmars-d-learn
mailing list