• Martin Thoma
  • Home
  • Categories
  • Tags
  • Archives
  • Support me

C Puzzle #2

Contents

  • C Puzzle #2
    • Answer
    • Expected output
    • Explanation
    • How to fix it

What is the output of the following script? Why? How can it be fixed to get the expected output?

#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#include <stdio.h>

int main() {
    uint64_t testvar;

    testvar = 1<<30;
    printf("2^30 = %" PRIu64 "\n", testvar);

    testvar = 1<<31;
    printf("2^31 = %" PRIu64 "\n", testvar);

    return 0;
}

. . . . . . . . . . . . . . . . .

Answer

2^30 = 1073741824
2^31 = 18446744071562067968

Expected output

2^30 = 1073741824
2^31 = 2147483648

Explanation

1<<30 does a bitshift for int, not for uint64_t

How to fix it

Add a typecast:

#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#include <stdio.h>

int main() {
    uint64_t testvar;

    testvar = 1<<30;
    printf("2^30 = %" PRIu64 "\n", testvar);

    testvar = ((uint64_t) 1)<<31;
    printf("2^31 = %" PRIu64 "\n", testvar);

    return 0;
}

Published

Okt 20, 2012
by Martin Thoma

Category

Code

Tags

  • C 23
  • Programming 52
  • puzzle 22

Contact

  • Martin Thoma - A blog about Code, the Web and Cyberculture
  • E-mail subscription
  • RSS-Feed
  • Privacy/Datenschutzerklärung
  • Impressum
  • Powered by Pelican. Theme: Elegant by Talha Mansoor