kit

kit
git clone https://git.ryansepassi.com/git/kit.git
Log | Files | Refs | README

conv_intnarrow.c (1211B)


      1 /* Integer narrowing: long -> int -> short -> char (truncation).
      2  * Narrowing drops high bits; the backend models this with register-width
      3  * selection and masking moves. Source values have set bits above each target
      4  * width so the truncation is observable. volatile sources defeat folding.
      5  *
      6  *   L  = 0x1_0000_002A      : (int)L    = 0x2A   = 42      (use w view)
      7  *   I  = 0x1234_0040        : (short)I  = 0x0040 = 64
      8  *   I2 = 0x0000_12AB        : (char)I2  = 0xAB sign-extends; use unsigned char
      9  * Combine so the answer is exactly 42. */
     10 int test_main(void) {
     11   volatile long L = 0x10000002AL;           /* low 32 bits = 0x2A = 42 */
     12   volatile int I = 0x12340040;              /* low 16 bits = 0x40 = 64 */
     13   volatile unsigned int I2 = 0x000012ABu;   /* low  8 bits = 0xAB = 171 */
     14   int n_int = (int)L;                       /* 42  (truncate 64->32) */
     15   short n_short = (short)I;                 /* 64  (truncate 32->16) */
     16   unsigned char n_char = (unsigned char)I2; /* 171 (truncate 32->8)  */
     17   /* 42 == n_int already; verify narrowing and fold the others away. */
     18   int extra = (n_short - 64) + ((int)n_char - 171); /* 0 */
     19   return n_int + extra;                             /* 42 + 0 = 42 */
     20 }