Unexpected result with right shift after bitwise negationWhat are bitwise shift (bit-shift) operators and how do they work?Improve INSERT-per-second performance of SQLite?Right shift two's complement number like an unsigned intbit shifting in C, unexpected resultRight shift with zeros at the beginningUnexepected behavior from multiple bitwise shifts on the same lineUnexpected Result After Arithmetically Right ShiftingWhy unsigned int right shift is always filled with '1'Unusual behavior with shift-right bitwise operatorprintf() function in loop #3 gives unexpected result

How to recover a single blank shot from a film camera

How "fast" do astronomical events occur?

Is it a bad idea to have a pen name with only an initial for a surname?

Time at 1G acceleration to travel 100 000 light years

How did space travel spread throughout the Star Wars galaxy?

SQL Server has encountered occurences of I/O requests taking longer than 15 seconds

Common Marsupials and Rare Antelopes

How can I maintain game balance while allowing my player to craft genuinely useful items?

What could be the physiological mechanism for a biological Geiger counter?

How to prevent cables getting intertwined

1960s sci-fi anthology with a Viking fighting a U.S. army MP on the cover

Are there any individual aliens that have gained superpowers in the Marvel universe?

Why do you need to heat the pan before heating the olive oil?

How can I ping multiple IP addresses at the same time?

In windows systems, is renaming files functionally similar to deleting them?

Bash function: Execute $@ command with each argument in sequence executed separately

I have found ports on my Samsung smart tv running a display service. What can I do with it?

I wish, I yearn, for an answer to this riddle

What is "dot" sign in •NO?

Why is Skinner so awkward in Hot Fuzz?

How did Avada Kedavra get its name?

What do I put on my resume to make the company i'm applying to think i'm mature enough to handle a job?

What is the precise meaning of "подсел на мак"?

How to make a villain when your PCs are villains?



Unexpected result with right shift after bitwise negation


What are bitwise shift (bit-shift) operators and how do they work?Improve INSERT-per-second performance of SQLite?Right shift two's complement number like an unsigned intbit shifting in C, unexpected resultRight shift with zeros at the beginningUnexepected behavior from multiple bitwise shifts on the same lineUnexpected Result After Arithmetically Right ShiftingWhy unsigned int right shift is always filled with '1'Unusual behavior with shift-right bitwise operatorprintf() function in loop #3 gives unexpected result






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








21















I expected that below code will output 10 because (~port) equal to 10100101
So, when we right shift it by 4 we get 00001010 which is 10.
But the output is 250! Why?



int main()

uint8_t port = 0x5a;
uint8_t result_8 = (~port) >> 4;
//result_8 = result_8 >> 4;

printf("%i", result_8);

return 0;










share|improve this question






























    21















    I expected that below code will output 10 because (~port) equal to 10100101
    So, when we right shift it by 4 we get 00001010 which is 10.
    But the output is 250! Why?



    int main()

    uint8_t port = 0x5a;
    uint8_t result_8 = (~port) >> 4;
    //result_8 = result_8 >> 4;

    printf("%i", result_8);

    return 0;










    share|improve this question


























      21












      21








      21


      4






      I expected that below code will output 10 because (~port) equal to 10100101
      So, when we right shift it by 4 we get 00001010 which is 10.
      But the output is 250! Why?



      int main()

      uint8_t port = 0x5a;
      uint8_t result_8 = (~port) >> 4;
      //result_8 = result_8 >> 4;

      printf("%i", result_8);

      return 0;










      share|improve this question
















      I expected that below code will output 10 because (~port) equal to 10100101
      So, when we right shift it by 4 we get 00001010 which is 10.
      But the output is 250! Why?



      int main()

      uint8_t port = 0x5a;
      uint8_t result_8 = (~port) >> 4;
      //result_8 = result_8 >> 4;

      printf("%i", result_8);

      return 0;







      c bit-manipulation






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Apr 15 at 1:02









      John Kugelman

      254k56413465




      254k56413465










      asked Apr 15 at 0:46









      IslamIslam

      1296




      1296






















          1 Answer
          1






          active

          oldest

          votes


















          28














          C promotes uint8_t to int before doing operations on it. So:




          1. port is promoted to signed integer 0x0000005a.


          2. ~ inverts it giving 0xffffffa5.

          3. An arithmetic shift returns 0xfffffffa.

          4. It's truncated back into a uint8_t giving 0xfa == 250.

          To fix that, either truncate the temporary result:



          uint8_t result_8 = (uint8_t)(~port) >> 4;


          mask it:



          uint8_t result_8 = (~port & 0xff) >> 4;


          or xor it (thanks @Nayuki!):



          uint8_t result_8 = (port ^ 0xff) >> 4;





          share|improve this answer

























          • you're right but i think C doesn't promote only uint8_t but also unsigned char because i tested it with unsigned char too and got the same result! Am i right?

            – Islam
            Apr 15 at 1:04






          • 13





            uint8_t is, very likely, a synonym of unsigned char on your system. The promotion rules apply to all integral types smaller than int.

            – ybungalobill
            Apr 15 at 1:07






          • 7





            Or explicitly only flip the low 8 bits: result = (port ^ 0xFF) >> 4;

            – Nayuki
            Apr 15 at 2:16











          • @Nayuki: that's a good one too!

            – ybungalobill
            Apr 15 at 2:26






          • 2





            @TomášZato: Yes. See en.cppreference.com/w/cpp/language/…

            – ybungalobill
            Apr 15 at 9:02












          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55681351%2funexpected-result-with-right-shift-after-bitwise-negation%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          28














          C promotes uint8_t to int before doing operations on it. So:




          1. port is promoted to signed integer 0x0000005a.


          2. ~ inverts it giving 0xffffffa5.

          3. An arithmetic shift returns 0xfffffffa.

          4. It's truncated back into a uint8_t giving 0xfa == 250.

          To fix that, either truncate the temporary result:



          uint8_t result_8 = (uint8_t)(~port) >> 4;


          mask it:



          uint8_t result_8 = (~port & 0xff) >> 4;


          or xor it (thanks @Nayuki!):



          uint8_t result_8 = (port ^ 0xff) >> 4;





          share|improve this answer

























          • you're right but i think C doesn't promote only uint8_t but also unsigned char because i tested it with unsigned char too and got the same result! Am i right?

            – Islam
            Apr 15 at 1:04






          • 13





            uint8_t is, very likely, a synonym of unsigned char on your system. The promotion rules apply to all integral types smaller than int.

            – ybungalobill
            Apr 15 at 1:07






          • 7





            Or explicitly only flip the low 8 bits: result = (port ^ 0xFF) >> 4;

            – Nayuki
            Apr 15 at 2:16











          • @Nayuki: that's a good one too!

            – ybungalobill
            Apr 15 at 2:26






          • 2





            @TomášZato: Yes. See en.cppreference.com/w/cpp/language/…

            – ybungalobill
            Apr 15 at 9:02
















          28














          C promotes uint8_t to int before doing operations on it. So:




          1. port is promoted to signed integer 0x0000005a.


          2. ~ inverts it giving 0xffffffa5.

          3. An arithmetic shift returns 0xfffffffa.

          4. It's truncated back into a uint8_t giving 0xfa == 250.

          To fix that, either truncate the temporary result:



          uint8_t result_8 = (uint8_t)(~port) >> 4;


          mask it:



          uint8_t result_8 = (~port & 0xff) >> 4;


          or xor it (thanks @Nayuki!):



          uint8_t result_8 = (port ^ 0xff) >> 4;





          share|improve this answer

























          • you're right but i think C doesn't promote only uint8_t but also unsigned char because i tested it with unsigned char too and got the same result! Am i right?

            – Islam
            Apr 15 at 1:04






          • 13





            uint8_t is, very likely, a synonym of unsigned char on your system. The promotion rules apply to all integral types smaller than int.

            – ybungalobill
            Apr 15 at 1:07






          • 7





            Or explicitly only flip the low 8 bits: result = (port ^ 0xFF) >> 4;

            – Nayuki
            Apr 15 at 2:16











          • @Nayuki: that's a good one too!

            – ybungalobill
            Apr 15 at 2:26






          • 2





            @TomášZato: Yes. See en.cppreference.com/w/cpp/language/…

            – ybungalobill
            Apr 15 at 9:02














          28












          28








          28







          C promotes uint8_t to int before doing operations on it. So:




          1. port is promoted to signed integer 0x0000005a.


          2. ~ inverts it giving 0xffffffa5.

          3. An arithmetic shift returns 0xfffffffa.

          4. It's truncated back into a uint8_t giving 0xfa == 250.

          To fix that, either truncate the temporary result:



          uint8_t result_8 = (uint8_t)(~port) >> 4;


          mask it:



          uint8_t result_8 = (~port & 0xff) >> 4;


          or xor it (thanks @Nayuki!):



          uint8_t result_8 = (port ^ 0xff) >> 4;





          share|improve this answer















          C promotes uint8_t to int before doing operations on it. So:




          1. port is promoted to signed integer 0x0000005a.


          2. ~ inverts it giving 0xffffffa5.

          3. An arithmetic shift returns 0xfffffffa.

          4. It's truncated back into a uint8_t giving 0xfa == 250.

          To fix that, either truncate the temporary result:



          uint8_t result_8 = (uint8_t)(~port) >> 4;


          mask it:



          uint8_t result_8 = (~port & 0xff) >> 4;


          or xor it (thanks @Nayuki!):



          uint8_t result_8 = (port ^ 0xff) >> 4;






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Apr 15 at 5:37

























          answered Apr 15 at 0:50









          ybungalobillybungalobill

          47.9k1399166




          47.9k1399166












          • you're right but i think C doesn't promote only uint8_t but also unsigned char because i tested it with unsigned char too and got the same result! Am i right?

            – Islam
            Apr 15 at 1:04






          • 13





            uint8_t is, very likely, a synonym of unsigned char on your system. The promotion rules apply to all integral types smaller than int.

            – ybungalobill
            Apr 15 at 1:07






          • 7





            Or explicitly only flip the low 8 bits: result = (port ^ 0xFF) >> 4;

            – Nayuki
            Apr 15 at 2:16











          • @Nayuki: that's a good one too!

            – ybungalobill
            Apr 15 at 2:26






          • 2





            @TomášZato: Yes. See en.cppreference.com/w/cpp/language/…

            – ybungalobill
            Apr 15 at 9:02


















          • you're right but i think C doesn't promote only uint8_t but also unsigned char because i tested it with unsigned char too and got the same result! Am i right?

            – Islam
            Apr 15 at 1:04






          • 13





            uint8_t is, very likely, a synonym of unsigned char on your system. The promotion rules apply to all integral types smaller than int.

            – ybungalobill
            Apr 15 at 1:07






          • 7





            Or explicitly only flip the low 8 bits: result = (port ^ 0xFF) >> 4;

            – Nayuki
            Apr 15 at 2:16











          • @Nayuki: that's a good one too!

            – ybungalobill
            Apr 15 at 2:26






          • 2





            @TomášZato: Yes. See en.cppreference.com/w/cpp/language/…

            – ybungalobill
            Apr 15 at 9:02

















          you're right but i think C doesn't promote only uint8_t but also unsigned char because i tested it with unsigned char too and got the same result! Am i right?

          – Islam
          Apr 15 at 1:04





          you're right but i think C doesn't promote only uint8_t but also unsigned char because i tested it with unsigned char too and got the same result! Am i right?

          – Islam
          Apr 15 at 1:04




          13




          13





          uint8_t is, very likely, a synonym of unsigned char on your system. The promotion rules apply to all integral types smaller than int.

          – ybungalobill
          Apr 15 at 1:07





          uint8_t is, very likely, a synonym of unsigned char on your system. The promotion rules apply to all integral types smaller than int.

          – ybungalobill
          Apr 15 at 1:07




          7




          7





          Or explicitly only flip the low 8 bits: result = (port ^ 0xFF) >> 4;

          – Nayuki
          Apr 15 at 2:16





          Or explicitly only flip the low 8 bits: result = (port ^ 0xFF) >> 4;

          – Nayuki
          Apr 15 at 2:16













          @Nayuki: that's a good one too!

          – ybungalobill
          Apr 15 at 2:26





          @Nayuki: that's a good one too!

          – ybungalobill
          Apr 15 at 2:26




          2




          2





          @TomášZato: Yes. See en.cppreference.com/w/cpp/language/…

          – ybungalobill
          Apr 15 at 9:02






          @TomášZato: Yes. See en.cppreference.com/w/cpp/language/…

          – ybungalobill
          Apr 15 at 9:02




















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55681351%2funexpected-result-with-right-shift-after-bitwise-negation%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Tamil (spriik) Luke uk diar | Nawigatjuun

          Align equal signs while including text over equalitiesAMS align: left aligned text/math plus multicolumn alignmentMultiple alignmentsAligning equations in multiple placesNumbering and aligning an equation with multiple columnsHow to align one equation with another multline equationUsing \ in environments inside the begintabularxNumber equations and preserving alignment of equal signsHow can I align equations to the left and to the right?Double equation alignment problem within align enviromentAligned within align: Why are they right-aligned?

          Training a classifier when some of the features are unknownWhy does Gradient Boosting regression predict negative values when there are no negative y-values in my training set?How to improve an existing (trained) classifier?What is effect when I set up some self defined predisctor variables?Why Matlab neural network classification returns decimal values on prediction dataset?Fitting and transforming text data in training, testing, and validation setsHow to quantify the performance of the classifier (multi-class SVM) using the test data?How do I control for some patients providing multiple samples in my training data?Training and Test setTraining a convolutional neural network for image denoising in MatlabShouldn't an autoencoder with #(neurons in hidden layer) = #(neurons in input layer) be “perfect”?