Unexpected result with right shift after bitwise negation Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 00:00UTC (8:00pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!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

AppleTVs create a chatty alternate WiFi network

Would it be easier to apply for a UK visa if there is a host family to sponsor for you in going there?

What is the difference between globalisation and imperialism?

A term for a woman complaining about things/begging in a cute/childish way

Is it fair for a professor to grade us on the possession of past papers?

Belief In God or Knowledge Of God. Which is better?

What is Adi Shankara referring to when he says "He has Vajra marks on his feet"?

Converted a Scalar function to a TVF function for parallel execution-Still running in Serial mode

QGIS virtual layer functionality does not seem to support memory layers

How to draw/optimize this graph with tikz

How to plot logistic regression decision boundary?

How come Sam didn't become Lord of Horn Hill?

Did any compiler fully use 80-bit floating point?

What does Turing mean by this statement?

How does the math work when buying airline miles?

Crossing US/Canada Border for less than 24 hours

Search between two dates with specific time with each date

How fail-safe is nr as stop bytes?

What's the meaning of "fortified infraction restraint"?

Quadrilaterals with equal sides

Strange behavior of Object.defineProperty() in JavaScript

What order were files/directories outputted in dir?

Why is it faster to reheat something than it is to cook it?

How many time did Arya actually used needle?



Unexpected result with right shift after bitwise negation



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








17















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






























    17















    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


























      17












      17








      17


      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

      249k54407460




      249k54407460










      asked Apr 15 at 0:46









      IslamIslam

      1096




      1096






















          1 Answer
          1






          active

          oldest

          votes


















          26














          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






          • 11





            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









          26














          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






          • 11





            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
















          26














          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






          • 11





            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














          26












          26








          26







          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

          46.6k1397163




          46.6k1397163












          • 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






          • 11





            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






          • 11





            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




          11




          11





          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

          Helsingborg Esperantistoj el Helsingborg | Vidu ankaŭ | Navigada menuo1 ŝanĝostabila versiopatrolita1 ŝanĝostabila versiopatrolita56°03′N 12°42′O  /  56.05°N, 12.7°O / 56.05; 12.7 (Helsingborg)56°03′N 12°42′O  /  56.05°N, 12.7°O / 56.05; 12.7 (Helsingborg)Helsingborg en la Vikimedia KomunejoKategorio Helsingborg en la Vikimedia KomunejoHelsingborg en la Vikimedia KomunejoKategorio Helsingborg en la Vikimedia Komunejo

          Linux Checkpoint SNX tool configuration issuesgetting Checkpoint VPN SSL Network Extender working in the command lineL2TP IPsec VPN client configurationOpenvpn stops respondingIssues with getting a tun0 connection to route any and all connections from eth0 to be made to this interface and if not working dropHow to setup port forwarding properly in FreeBsd 11?Getting certificate verify failed error in a Python applicationssh is unable to connect to server in VPNVPN SSL Network Extender in Firefoxgetting Checkpoint VPN SSL Network Extender working in the command lineisc-dhcp-server configurationUsing Checkpoint VPN SSL Network Extender CLI with certificate

          NetworkManager fails with “Could not find source connection”Trouble connecting to VPN using network-manager, while command line worksHow can I be notified about state changes to a VPN adapterBacktrack 5 R3 - Refuses to connect to VPNFeed all traffic through OpenVPN for a specific network namespace onlyRun daemon on startup in Debian once openvpn connection establishedpfsense tcp connection between openvpn and lan is brokenInternet connection problem with web browsers onlyWhy does NetworkManager explicitly support tun/tap devices?Browser issues with VPNTwo IP addresses assigned to the same network card - OpenVPN issues?Cannot connect to WiFi with nmcli, although secrets are provided