Unexpected result with right shift after bitwise negation Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) The Ask Question Wizard is Live! Data science time! April 2019 and salary with experienceWhat 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 say that you spent the night with someone, you were only sleeping and nothing else?

Limit for e and 1/e

Area of a 2D convex hull

Why does this iterative way of solving of equation work?

I'm thinking of a number

Need a suitable toxic chemical for a murder plot in my novel

Can a zero nonce be safely used with AES-GCM if the key is random and never used again?

What would be Julian Assange's expected punishment, on the current English criminal law?

Mortgage adviser recommends a longer term than necessary combined with overpayments

What to do with post with dry rot?

How can players take actions together that are impossible otherwise?

What did Darwin mean by 'squib' here?

What do you call the holes in a flute?

Was credit for the black hole image misattributed?

Why is there no army of Iron-Mans in the MCU?

Using "nakedly" instead of "with nothing on"

Problem when applying foreach loop

Replacing HDD with SSD; what about non-APFS/APFS?

Do working physicists consider Newtonian mechanics to be "falsified"?

Complexity of many constant time steps with occasional logarithmic steps

Why don't the Weasley twins use magic outside of school if the Trace can only find the location of spells cast?

How to market an anarchic city as a tourism spot to people living in civilized areas?

Strange behaviour of Check

How to colour the US map with Yellow, Green, Red and Blue to minimize the number of states with the colour of Green



Unexpected result with right shift after bitwise negation



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)
The Ask Question Wizard is Live!
Data science time! April 2019 and salary with experienceWhat 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;








6















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






























    6















    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


























      6












      6








      6


      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 1 hour ago









      John Kugelman

      249k54407460




      249k54407460










      asked 1 hour ago









      IslamIslam

      545




      545






















          1 Answer
          1






          active

          oldest

          votes


















          11














          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;


          or mask it:



          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
            1 hour ago






          • 3





            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
            1 hour ago











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

            – Nayuki
            8 mins ago











          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









          11














          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;


          or mask it:



          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
            1 hour ago






          • 3





            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
            1 hour ago











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

            – Nayuki
            8 mins ago















          11














          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;


          or mask it:



          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
            1 hour ago






          • 3





            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
            1 hour ago











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

            – Nayuki
            8 mins ago













          11












          11








          11







          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;


          or mask it:



          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;


          or mask it:



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






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered 1 hour ago









          ybungalobillybungalobill

          46.2k1396163




          46.2k1396163












          • 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
            1 hour ago






          • 3





            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
            1 hour ago











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

            – Nayuki
            8 mins ago

















          • 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
            1 hour ago






          • 3





            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
            1 hour ago











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

            – Nayuki
            8 mins ago
















          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
          1 hour ago





          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
          1 hour ago




          3




          3





          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
          1 hour ago





          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
          1 hour ago













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

          – Nayuki
          8 mins ago





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

          – Nayuki
          8 mins ago



















          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

          How to create a command for the “strange m” symbol in latex? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)How do you make your own symbol when Detexify fails?Writing bold small caps with mathpazo packageplus-minus symbol with parenthesis around the minus signGreek character in Beamer document titleHow to create dashed right arrow over symbol?Currency symbol: Turkish LiraDouble prec as a single symbol?Plus Sign Too Big; How to Call adfbullet?Is there a TeX macro for three-legged pi?How do I get my integral-like symbol to align like the integral?How to selectively substitute a letter with another symbol representing the same letterHow do I generate a less than symbol and vertical bar that are the same height?

          Българска екзархия Съдържание История | Български екзарси | Вижте също | Външни препратки | Литература | Бележки | НавигацияУстав за управлението на българската екзархия. Цариград, 1870Слово на Ловешкия митрополит Иларион при откриването на Българския народен събор в Цариград на 23. II. 1870 г.Българската правда и гръцката кривда. От С. М. (= Софийски Мелетий). Цариград, 1872Предстоятели на Българската екзархияПодмененият ВеликденИнформационна агенция „Фокус“Димитър Ризов. Българите в техните исторически, етнографически и политически граници (Атлас съдържащ 40 карти). Berlin, Königliche Hoflithographie, Hof-Buch- und -Steindruckerei Wilhelm Greve, 1917Report of the International Commission to Inquire into the Causes and Conduct of the Balkan Wars

          Category:Tremithousa Media in category "Tremithousa"Navigation menuUpload media34° 49′ 02.7″ N, 32° 26′ 37.32″ EOpenStreetMapGoogle EarthProximityramaReasonatorScholiaStatisticsWikiShootMe