<div class="gmail_quote">On Wed, May 16, 2012 at 11:03 AM, Regan Heath <span dir="ltr"><<a href="mailto:regan@netmail.co.nz" target="_blank">regan@netmail.co.nz</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">

<div class="HOEnZb"><div class="h5">On Wed, 16 May 2012 15:24:33 +0100, ref2401 <<a href="mailto:refactor24@gmail.com" target="_blank">refactor24@gmail.com</a>> wrote:<br>
<br>
<blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">
i have an array of ubytes. how can i convert two adjacent ubytes from the array to an integer?<br>
<br>
pseudocode example:<br>
ubyte[5] array = createArray();<br>
int value = array[2..3];<br>
<br>
is there any 'memcpy' method or something else to do this?<br>
</blockquote>
<br></div></div>
You don't need to "copy" the data, just tell the compiler to "pretend" it's a short (in this case, for 2 bytes) then copy the value/assign to an int. e.g.<br>
<br>
import std.stdio;<br>
<br>
void main()<br>
{<br>
        ubyte[5] array = [ 0xFF, 0xFF, 0x01, 0x00, 0xFF ];<br>
        int value = *cast(short*)array[2..3].ptr;<br>
        writefln("Result = %s", value);<br>
}<br>
<br>
The line:<br>
  int value = *cast(short*)array[2..3].ptr;<br>
<br>
1. slices 2 bytes from the array.<br>
2. obtains the ptr to them<br>
3. casts the ptr to short*<br>
4. copies the value pointed at by the short* ptr to an int<br>
<br>
You may need to worry about little/big endian issues, see:<br>
<a href="http://en.wikipedia.org/wiki/Endianness" target="_blank">http://en.wikipedia.org/wiki/<u></u>Endianness</a><br>
<br>
The above code outputs "Result = 1" on my little-endian x86 desktop machine but would output "Result = 256" on a big-endian machine.<span class="HOEnZb"><font color="#888888"><br>
<br>
R<br>
<br></font></span></blockquote><div><br></div><div>Unfortunately, this is undefined behavior because you're breaking alignment rules. On x86, this will just cause a slow load from memory. On ARM, this will either crash your program with a bus error on newer hardware or give you a gibberish value on ARMv6 and older.</div>

<div>Declaring a short, getting a pointer to it, and casting that pointer to a ubyte* to copy into it is fine, but casting a ubyte* to a short* will cause a 2-byte load from a 1-byte aligned address, which leads down the yellow brick road to pain.</div>

</div>