What it the preferred method to write a class to a file?

Regan Heath regan at netwin.co.nz
Sun Jul 23 18:41:12 PDT 2006


On Sun, 23 Jul 2006 17:26:57 -0700, Charles D Hixson  
<charleshixsn at earthlink.net> wrote:
> Jarrett Billingsley wrote:
>> "Charles D Hixson" <charleshixsn at earthlink.net> wrote in message
>> news:ea0rll$5h9$1 at digitaldaemon.com...
>>
>>> P.S.:  Is there a standard library routine for converting
>>> between strings of length 4 and uint-s?  If so I wasn't able
>>> to find it.  If not, I wasn't able to determine that it
>>> didn't exist.  (That would have made writing the sig more
>>> efficient.)
>>
>> You don't even need a routine to do it.
>>
>> char[] sig = "help";
>> uint s = *cast(uint*)sig.ptr;
>>
>> And the other way..
>>
>> uint s = 0xAABBCCDD;
>> char[] sig = new char[4];
>> *cast(uint*)sig.ptr = s;
>>
>>
> O, dear.  Yes, I see it.
> But one of the things that cause me to prefer D over C is
> the ability to avoid pointer manipulation, which to me seem
> extremely hazardous and, when one gets beyond simple cases,
> quite confusing.  (And unmaintainable.)

Some alternatives to consider...

import std.stdio;

uint char_to_uint(char[] str)
{
	return *cast(uint*)str.ptr;
}

uint char_to_uint_a(char[] str)
{
	uint i = 0;
	for(int j = 3; j >= 0; j--) {
		i <<= 8;
		i |= str[j];
	}
	return i;
}

/*
Option #1
Note: .dup is required the local 'i' becomes invalid after the function  
returns
char[] uint_to_char(uint i)
{
	char[] str = new char[4];
	*cast(uint*)str.ptr = i;
	return str.dup;
}

Option #2
Note: no dup required, we're copying the data to the new array.
char[] uint_to_char(uint i)
{
	char[] str = new char[4];
	str[] = (cast(char*)&i)[0..4];
	return str;
}
*/

//Note: same as #1 but involves 1 less temporary array.
char[] uint_to_char(uint i)
{
	return (cast(char*)&i)[0..4].dup;
}

char[] uint_to_char_a(uint i)
{
	char[] str = new char[4];
	foreach(inout c; str) {
		c = i&0xFF;
		i >>= 8;
	}
	return str;
}

void main()
{
	char[] str = "abcd";
	writefln("%b (%d)",char_to_uint(str),char_to_uint(str));
	writefln("%b (%d)",char_to_uint_a(str),char_to_uint_a(str));
	writefln(uint_to_char(char_to_uint(str)));
	writefln(uint_to_char_a(char_to_uint(str)));
}

Also, have you considered the 'endian' issues of storing data in a binary  
format. See:
http://en.wikipedia.org/wiki/Endian

Specifically, if you plan to use a file saved on a machine which is little  
endian, i.e. your typical x86 pentium/amd and transfer it to a big endian  
machine i.e. a solaris sparc server or powerPC and load it. If you do then  
you will need to decide on an endian format to save to and load from and  
therefore perform conversion on one of the systems (and not the other).

To perform conversion you would simply modify the _a functions above to  
process the characters in reverse order.

Regan



More information about the Digitalmars-d-learn mailing list