views:

358

answers:

3

Hi,

select convert(varbinary(8), 1) in MS SQL Server produces output : 0x00000001

On assigning the above query to dataset in Delphi, and accessing field value, we get byte array as [1, 0, 0, 0] . So Bytes[0] contains 1.

When I use IntToHex() on this bytes array it would result me value as "10000000" .

Why is IntToHex considering it in reverse order?

Thanks & Regards,

Pavan.

A: 

This seems to be a little/big endian problem. Just reverse the byte array or the return value from IntToHex. Another way would be to do it yourself:

myInt = Bytes[0];
Inc(myInt, (Bytes[1] shl 8));
Inc(myInt, (Bytes[2] shl 16));
Inc(myInt, (Bytes[3] shl 24));

Also be careful with the sign. Is the SQL value signed or unsigned - the Delphi datatype should match this (int/longint is signed, Longword/Cardinal is unsigned - see here or in the Delphi Help).

schnaader
A: 

Because the x86 CPU uses little-endian numbers, a numbering system which orders its bytes in reverse order. You'll need to swap the byte order to get the right value.

Mason Wheeler
+2  A: 

I think you forgot to include a reference to the code where you're somehow calling IntToHex on a TBytes array. It's from the answer to your previous question, how to convert byte array to its hex representation in Delphi.

In my answer, I forgot to account for how a pointer to an array of bytes would have the bytes in big-endian order while IntToHex (and everything else on x86) expects them in little-endian order. The solution is to switch them around. I used this function:

function Swap32(value: Integer): Integer;
asm
  bswap eax
end;

In the meantime, I fixed my answer to account for that.

Rob Kennedy