3

Problem to solve:

Write hexadecimal value of 32-bit variable i (type Longint) after executing code in Pascal. Code will translate for little-endian platform. i:=-20; i:=($FFFF xor (i shr 2)) and not($50 shl 16);

What I need to know: what happens in brackets (i shr 2) and ($50 shl 16).

What I thought: i (-20) in hexadecimal: FFEC (but maybe thanks to little-endian it's CEFF). ($50 shl 16) - I thought that because $50 is only 8 bit, shl 16 will just make it to zero. Or will it become $500000?

mvw
  • 5,075
  • 1
  • 28
  • 34
Nope nope
  • 49
  • 1
  • 7
  • This is ambiguous, and depends on the type of the integer type (since the result of "$50 shl 16" depends on with how many bits it is evaluated). Might give different results in Turbo pascal (16-bits registers and evaluation) and freepascal (32-bit evaluation) – Marco van de Voort Feb 18 '15 at 12:33

1 Answers1

2

i shr 2 = shift right i by 2 positions, which is roughly i = i / 4

$50 shl 16 = shift left $50 by 16 positions, this is done in the register (see here)

$0000 0050 -> $0050 0000

Now going for the calculation of i:

The -20 of a 32 bit value:

$ffff ffec

The SHR 2 of -20: (done in register)

ffff ffec -> 3fff fffb

Then the XOR (done in register)

0000 ffff
3fff fffb
----------
3fff 0004

Then the NOT of $0050 0000: (logical not = bit complement, not 2 complement)

0050 0000 -> ffaf ffff

Finally the AND: (in register)

3fff 0004
ffaf ffff
--------
3faf 0004

This is the value of 'i', as used in any register based calculation.

The little endianness only matters for the memory storage, where i is stored as 0400 af3f.

Community
  • 1
  • 1
mvw
  • 5,075
  • 1
  • 28
  • 34
  • Isn't the value of i brought from memory, where it is written in little endian? – Nope nope Feb 17 '15 at 13:41
  • The expression `i:=-20; i:=($FFFF xor (i shr 2)) and not($50 shl 16);` is independent from the endianess. A debugger would show the value $3faf0004 for i and if it displayed a memory dump there would be the bytes "0400af3f" visible – mvw Feb 17 '15 at 14:00