My thoughts & experiences with D so far, as a novice D coder

H. S. Teoh hsteoh at quickfur.ath.cx
Thu Mar 28 13:36:57 PDT 2013


On Thu, Mar 28, 2013 at 09:24:49PM +0100, Vidar Wahlberg wrote:
> To follow up with some new woes I'm currently struggling with: I'm
> storing some various values in an ubyte array. I discovered that it's
> probably std.bitmanip I wish to use in order to "convert" i.e.  an int
> to 4 bytes (although I went first to std.conv looking for this
> feature).
[...]

There are several ways to convert an int into 4 bytes:

1) Use a union:

	static assert(int.sizeof==4);
	ubyte[4] intToUbytes(int x) {
		union U {
			int i;
			ubyte[4] b;
		}
		U u;
		u.i = x;
		return u.b;
	}

2) Use bit operators:

	ubyte[4] intToUbytes(int x) {
		ubyte[4] bytes;

		// Note: this assumes little-endian. For big-endian,
		// reverse the order below.
		bytes[0] = x & 0xFF;
		bytes[1] = (x >> 8) & 0xFF;
		bytes[2] = (x >> 16) & 0xFF;
		bytes[3] = (x >> 24) & 0xFF;

		return bytes;
	}

3) Use a pointer cast (warning: un- at safe):

	ubyte[4] intToUbytes(int x) @system {
		ubyte[4] b;
		ubyte* ptr = cast(ubyte*)&x;
		b[0] = *ptr++;
		b[1] = *ptr++;
		b[2] = *ptr++;
		b[3] = *ptr;

		return b;
	}

4) Reinterpret a pointer (warning: un- at safe):

	ubyte[4] intToUbytes(int x) @system {
		return *cast(ubyte[4]*)&x;
	}

I'm sure there are several other ways to do it.

You don't need to use appender unless you're doing a lot of conversions
in one go.


--T


More information about the Digitalmars-d mailing list