-3

This is a two fold question .

  1. I have been reading up on the intricacies of how compilers process code and I am having this confusion. Both processes seem to be following the same logic of sign extension for signed integers. So is conversion simply implemented as an arithmetic right shift?

  2. One of the examples states a function as

    Int Fun1(unsigned word ) {
          Return (int) ((word << 24) >> 24 );
    }
    

    The argument passed is 0x87654321. Since this would be signed when converted to binary, how would the shift happen? My logic was that the left shift should extract the last 8 bits leaving 0 as the MSB and this would then we extended while right shifting. Is this logic correct?

Edit: I understand that the downvote is probably due to unspecified info. Assume a 32 bit big endian machine with two's complement for signed integers.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
surya
  • 253
  • 3
  • 9
  • You are asking in regards to twos-complement? – tijko Dec 03 '16 at 04:03
  • `word` is declared to be `unsigned`, so should compile to a logical rather than arithmetic shift. The conversion to a signed integer is performed after the shift. – Neapolitan Dec 03 '16 at 04:44
  • If `int` is 32-bit then `0x87654321` has type `unsigned int` – M.M Dec 03 '16 at 06:23
  • @m.m. typo corrected – surya Dec 03 '16 at 07:22
  • @neapolitan Thank you. I had missed the type of the argument. But even if the type is signed , does the logic remains the same, except the fact that the bits after shifting would be 1s(assuming the integer is negative ) instead of zeroes ? – surya Dec 03 '16 at 07:54
  • The endian (big, little or otherwise) is irrelevant to this question. – chux - Reinstate Monica Dec 03 '16 at 08:21
  • example don't compile. http://stackoverflow.com/questions/141525/what-are-bitwise-shift-bit-shift-operators-and-how-do-they-work – Stargateur Dec 03 '16 at 08:21

1 Answers1

1

Given OP's "Assume a 32 bit ... machine with two's complement for signed integers." (This implies 32-bit unsigned)

0x87654321 Since this would be signed when converted to binary

No. 0x87654321 is a hexadecimal constant. It has the type unsigned. It is not signed.


// Int Fun1(unsigned word ) {
int Fun1(unsigned word) {
      Return (int) ((word << 24) >> 24 );
}

Fun1(0x87654321) results in unsigned word having the value of 0x87654321. No type nor value conversion occurred.

word << 24 has the value of 0x21000000 and still the type of unsigned.

(word << 24) >> 24 has the value of 0x21 and still the type of unsigned.

Casting to int retains the same value of 0x21, but now type int.


So is conversion simply implemented as an arithmetic right shift ?

Doubtful, as no signed shifting is coded. C does not specify how the compiler realizes the C code. A pair of shifts, or a mask or a multiply/divide may have occurred.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256