Should a cast be used to truncate a long variable?Implicit type promotion rulesRegular cast vs. static_cast...

Is it possible to detect 100% of SQLi with a simple regex?

Does the US government have any planning in place to ensure there's no shortages of food, fuel, steel and other commodities?

How much light is too much?

Can you determine if focus is sharp without diopter adjustment if your sight is imperfect?

Why is Shelob considered evil?

Potential client has a problematic employee I can't work with

What does an unprocessed RAW file look like?

Critique vs nitpicking

If angels and devils are the same species, why would their mortal offspring appear physically different?

How to change a .eps figure to standalone class?

Other than edits for international editions, did Harry Potter and the Philosopher's Stone receive errata?

How do you funnel food off a cutting board?

How to not let the Identify spell spoil everything?

Is `Object` a function in javascript?

How is this property called for mod?

How can I give a Ranger advantage on a check due to Favored Enemy without spoiling the story for the player?

Equivalent of "illegal" for violating civil law

Illustrator to chemdraw

Is the fingering of thirds flexible or do I have to follow the rules?

What kind of places would goblins live in a fantasy setting with strong states?

Prevent Nautilus / Nemo from creating .Trash-1000 folder in mounted devices

What does からか mean?

Is it possible to rotate the Isolines on a Surface Using `MeshFunction`?

Converting very wide logos to square formats



Should a cast be used to truncate a long variable?


Implicit type promotion rulesRegular cast vs. static_cast vs. dynamic_castCast int to enum in C#Direct casting vs 'as' operator?When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used?Do I cast the result of malloc?Safely casting long to int in JavaImprove INSERT-per-second performance of SQLite?How do I truncate a .NET string?How to truncate a foreign key constrained table?Why don't Java's +=, -=, *=, /= compound assignment operators require casting?













6















I have a 16 bits unsigned variable. I need to split it in 8 bits chunks.



Is doing the following enough:



chunk_lsb = (uint8)variable;
chunk_msb = (uint8)(variable >> 8);


Or should I use a mask:



chunk_lsb = (uint8)(variable & 0xFFu);
chunk_msb = (uint8)((variable >> 8) & 0xFFu);


I know that both approaches work, I'm just looking for the best way to do it, if there is one. Maybe there's none and just use the cast to reduce calculations is the best way? What do you guys think?










share|improve this question

























  • I think both will generate same binary code. As the first solution is more readable, I would use this one. You just need to be sure that uint8 is 8-but on all platforms (i guess it is)

    – jaudo
    2 hours ago











  • Thank you @jaudo, that's also the direction I'm taking.

    – Soyding Mete
    2 hours ago






  • 6





    Sidenote: Standard stdint.h types such as uint8_t should be preferred instead of creating your own.

    – user694733
    1 hour ago
















6















I have a 16 bits unsigned variable. I need to split it in 8 bits chunks.



Is doing the following enough:



chunk_lsb = (uint8)variable;
chunk_msb = (uint8)(variable >> 8);


Or should I use a mask:



chunk_lsb = (uint8)(variable & 0xFFu);
chunk_msb = (uint8)((variable >> 8) & 0xFFu);


I know that both approaches work, I'm just looking for the best way to do it, if there is one. Maybe there's none and just use the cast to reduce calculations is the best way? What do you guys think?










share|improve this question

























  • I think both will generate same binary code. As the first solution is more readable, I would use this one. You just need to be sure that uint8 is 8-but on all platforms (i guess it is)

    – jaudo
    2 hours ago











  • Thank you @jaudo, that's also the direction I'm taking.

    – Soyding Mete
    2 hours ago






  • 6





    Sidenote: Standard stdint.h types such as uint8_t should be preferred instead of creating your own.

    – user694733
    1 hour ago














6












6








6








I have a 16 bits unsigned variable. I need to split it in 8 bits chunks.



Is doing the following enough:



chunk_lsb = (uint8)variable;
chunk_msb = (uint8)(variable >> 8);


Or should I use a mask:



chunk_lsb = (uint8)(variable & 0xFFu);
chunk_msb = (uint8)((variable >> 8) & 0xFFu);


I know that both approaches work, I'm just looking for the best way to do it, if there is one. Maybe there's none and just use the cast to reduce calculations is the best way? What do you guys think?










share|improve this question
















I have a 16 bits unsigned variable. I need to split it in 8 bits chunks.



Is doing the following enough:



chunk_lsb = (uint8)variable;
chunk_msb = (uint8)(variable >> 8);


Or should I use a mask:



chunk_lsb = (uint8)(variable & 0xFFu);
chunk_msb = (uint8)((variable >> 8) & 0xFFu);


I know that both approaches work, I'm just looking for the best way to do it, if there is one. Maybe there's none and just use the cast to reduce calculations is the best way? What do you guys think?







c casting mask truncate






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 2 hours ago







Soyding Mete

















asked 2 hours ago









Soyding MeteSoyding Mete

424




424













  • I think both will generate same binary code. As the first solution is more readable, I would use this one. You just need to be sure that uint8 is 8-but on all platforms (i guess it is)

    – jaudo
    2 hours ago











  • Thank you @jaudo, that's also the direction I'm taking.

    – Soyding Mete
    2 hours ago






  • 6





    Sidenote: Standard stdint.h types such as uint8_t should be preferred instead of creating your own.

    – user694733
    1 hour ago



















  • I think both will generate same binary code. As the first solution is more readable, I would use this one. You just need to be sure that uint8 is 8-but on all platforms (i guess it is)

    – jaudo
    2 hours ago











  • Thank you @jaudo, that's also the direction I'm taking.

    – Soyding Mete
    2 hours ago






  • 6





    Sidenote: Standard stdint.h types such as uint8_t should be preferred instead of creating your own.

    – user694733
    1 hour ago

















I think both will generate same binary code. As the first solution is more readable, I would use this one. You just need to be sure that uint8 is 8-but on all platforms (i guess it is)

– jaudo
2 hours ago





I think both will generate same binary code. As the first solution is more readable, I would use this one. You just need to be sure that uint8 is 8-but on all platforms (i guess it is)

– jaudo
2 hours ago













Thank you @jaudo, that's also the direction I'm taking.

– Soyding Mete
2 hours ago





Thank you @jaudo, that's also the direction I'm taking.

– Soyding Mete
2 hours ago




6




6





Sidenote: Standard stdint.h types such as uint8_t should be preferred instead of creating your own.

– user694733
1 hour ago





Sidenote: Standard stdint.h types such as uint8_t should be preferred instead of creating your own.

– user694733
1 hour ago












4 Answers
4






active

oldest

votes


















4














Since uint8 is unsigned, you don't have to do the masking:




6.3.1.3 Signed and unsigned integers




  1. When a value with integer type is converted to another integer type other than _ Bool , if the value
    can be represented by the new type, it is unchanged.

  2. Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting
    one more than the maximum value that can be represented in the new type until the value is in the
    range of the new type.
    60)

  3. Otherwise, the new type is signed and the value cannot be represented in it; either the result is
    implementation-defined or an implementation-defined signal is raised.




However, most likely both will result in the same compiler output. I usually add the mask because it makes clear what code is supposed to do, and makes the cast unnecessary.






share|improve this answer



















  • 1





    Except, C has nasty integer promotion, so if you try to do the same thing and left shift, the program may implode in undefined behavior. In this particular case we get away since it is right shift of a positive number.

    – Lundin
    1 hour ago











  • Also, the cast makes the loss of precision clearly intentional. Many compilers can emit warning on loss of precision, which can extremely important. (I'm thinking of noobs who are so certain that "size_t and pointers are really just unsigned int...)

    – Andrew Henle
    1 hour ago



















3














It isn't clear what type variable is. Without that specified, we can only speculate.



But in general, you should avoid bit shifting on signed integer types, as that leads to various forms of poorly-defined behavior. This in turn means that you have to be careful with small integer types too, because they get promoted to signed int. See Implicit type promotion rules.



The specific case of (uint8)((variable >> 8) & 0xFFu); is safe if variable is unsigned. Otherwise it is unsafe, since right-shifting a negative value leads to implementation-defined behavior (arithmetic or logical shift).



variable << 8 will invoke undefined behavior on 16 bit systems in case variable is a small integer type, or an int16_t.



The safest, most portable way no matter left/right shift is therefore this:



chunk_lsb = variable;
chunk_msb = ((unsigned int)variable >> 8);


Though you might want to be overly explicit in order to silence all compiler warnings:



chunk_lsb = (uint8_t) (variable & 0xFFu);
chunk_msb = (uint8_t) ( (unsigned int)variable>>8 & 0xFFu );





share|improve this answer































    2














    If chunk_lsb is an 8 bit object, use cast or mask (not both). Useful in quieting pedantic warnings about range reduction. I prefer the mask - unless the compiler is picky.



    uint8_t chunk_lsb = (uint8_t) variable;
    // or
    uint8_t chunk_lsb = variable & 0xFFu;


    Otherwise use the mask.



    unsigned chunk_lsb = variable & 0xFFu;





    share|improve this answer































      -1















      Maybe there's none and just use the cast to reduce calculations is the best way?




      General speaking, the asm code will be the same, so in terms of speed, it does not matter which one you use:




      • masking: https://godbolt.org/z/Olrw3x

      • casting: https://godbolt.org/z/EEdvQZ



      What do you guys think?




      IMO, the first one is clearer, in terms of readability, but I cannot figure out a coding standard or guideline which supports my preference. Anyway, I would use a const variable if your preference is the second one, to remove magic numbers and make clearer that the purpose is masking (assuming that you have chosen a correct name for the const variable).






      share|improve this answer



















      • 1





        Anyway, I would use a const variable if your preference is the second one, to remove magic numbers and make clearer that the purpose is masking Anyone who thinks 0xFF in the context of bit masking is a "magic number" that has to be papered over with a variable is engaging in cargo-cult programming. What possible variable can be more clear than 0xFF as a bit mask? one_byte_bit_mask_0xFF?

        – Andrew Henle
        1 hour ago













      • IMO, if the purpose is to mask, the word mask is clearer than any (magic) number.

        – Jose
        1 hour ago











      • IMO, if the purpose is to mask, the word mask is clearer than any (magic) number Oh? How many bits does this mask: unsigned int result = input & mask; And no, I didn't DV.

        – Andrew Henle
        1 hour ago













      • 0xFF vs one_byte_bit_mask_0xFF vs mask, I choose the second one as the least-bad option.

        – Jose
        54 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%2f54866461%2fshould-a-cast-be-used-to-truncate-a-long-variable%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      4 Answers
      4






      active

      oldest

      votes








      4 Answers
      4






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      4














      Since uint8 is unsigned, you don't have to do the masking:




      6.3.1.3 Signed and unsigned integers




      1. When a value with integer type is converted to another integer type other than _ Bool , if the value
        can be represented by the new type, it is unchanged.

      2. Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting
        one more than the maximum value that can be represented in the new type until the value is in the
        range of the new type.
        60)

      3. Otherwise, the new type is signed and the value cannot be represented in it; either the result is
        implementation-defined or an implementation-defined signal is raised.




      However, most likely both will result in the same compiler output. I usually add the mask because it makes clear what code is supposed to do, and makes the cast unnecessary.






      share|improve this answer



















      • 1





        Except, C has nasty integer promotion, so if you try to do the same thing and left shift, the program may implode in undefined behavior. In this particular case we get away since it is right shift of a positive number.

        – Lundin
        1 hour ago











      • Also, the cast makes the loss of precision clearly intentional. Many compilers can emit warning on loss of precision, which can extremely important. (I'm thinking of noobs who are so certain that "size_t and pointers are really just unsigned int...)

        – Andrew Henle
        1 hour ago
















      4














      Since uint8 is unsigned, you don't have to do the masking:




      6.3.1.3 Signed and unsigned integers




      1. When a value with integer type is converted to another integer type other than _ Bool , if the value
        can be represented by the new type, it is unchanged.

      2. Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting
        one more than the maximum value that can be represented in the new type until the value is in the
        range of the new type.
        60)

      3. Otherwise, the new type is signed and the value cannot be represented in it; either the result is
        implementation-defined or an implementation-defined signal is raised.




      However, most likely both will result in the same compiler output. I usually add the mask because it makes clear what code is supposed to do, and makes the cast unnecessary.






      share|improve this answer



















      • 1





        Except, C has nasty integer promotion, so if you try to do the same thing and left shift, the program may implode in undefined behavior. In this particular case we get away since it is right shift of a positive number.

        – Lundin
        1 hour ago











      • Also, the cast makes the loss of precision clearly intentional. Many compilers can emit warning on loss of precision, which can extremely important. (I'm thinking of noobs who are so certain that "size_t and pointers are really just unsigned int...)

        – Andrew Henle
        1 hour ago














      4












      4








      4







      Since uint8 is unsigned, you don't have to do the masking:




      6.3.1.3 Signed and unsigned integers




      1. When a value with integer type is converted to another integer type other than _ Bool , if the value
        can be represented by the new type, it is unchanged.

      2. Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting
        one more than the maximum value that can be represented in the new type until the value is in the
        range of the new type.
        60)

      3. Otherwise, the new type is signed and the value cannot be represented in it; either the result is
        implementation-defined or an implementation-defined signal is raised.




      However, most likely both will result in the same compiler output. I usually add the mask because it makes clear what code is supposed to do, and makes the cast unnecessary.






      share|improve this answer













      Since uint8 is unsigned, you don't have to do the masking:




      6.3.1.3 Signed and unsigned integers




      1. When a value with integer type is converted to another integer type other than _ Bool , if the value
        can be represented by the new type, it is unchanged.

      2. Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting
        one more than the maximum value that can be represented in the new type until the value is in the
        range of the new type.
        60)

      3. Otherwise, the new type is signed and the value cannot be represented in it; either the result is
        implementation-defined or an implementation-defined signal is raised.




      However, most likely both will result in the same compiler output. I usually add the mask because it makes clear what code is supposed to do, and makes the cast unnecessary.







      share|improve this answer












      share|improve this answer



      share|improve this answer










      answered 1 hour ago









      user694733user694733

      11k12850




      11k12850








      • 1





        Except, C has nasty integer promotion, so if you try to do the same thing and left shift, the program may implode in undefined behavior. In this particular case we get away since it is right shift of a positive number.

        – Lundin
        1 hour ago











      • Also, the cast makes the loss of precision clearly intentional. Many compilers can emit warning on loss of precision, which can extremely important. (I'm thinking of noobs who are so certain that "size_t and pointers are really just unsigned int...)

        – Andrew Henle
        1 hour ago














      • 1





        Except, C has nasty integer promotion, so if you try to do the same thing and left shift, the program may implode in undefined behavior. In this particular case we get away since it is right shift of a positive number.

        – Lundin
        1 hour ago











      • Also, the cast makes the loss of precision clearly intentional. Many compilers can emit warning on loss of precision, which can extremely important. (I'm thinking of noobs who are so certain that "size_t and pointers are really just unsigned int...)

        – Andrew Henle
        1 hour ago








      1




      1





      Except, C has nasty integer promotion, so if you try to do the same thing and left shift, the program may implode in undefined behavior. In this particular case we get away since it is right shift of a positive number.

      – Lundin
      1 hour ago





      Except, C has nasty integer promotion, so if you try to do the same thing and left shift, the program may implode in undefined behavior. In this particular case we get away since it is right shift of a positive number.

      – Lundin
      1 hour ago













      Also, the cast makes the loss of precision clearly intentional. Many compilers can emit warning on loss of precision, which can extremely important. (I'm thinking of noobs who are so certain that "size_t and pointers are really just unsigned int...)

      – Andrew Henle
      1 hour ago





      Also, the cast makes the loss of precision clearly intentional. Many compilers can emit warning on loss of precision, which can extremely important. (I'm thinking of noobs who are so certain that "size_t and pointers are really just unsigned int...)

      – Andrew Henle
      1 hour ago













      3














      It isn't clear what type variable is. Without that specified, we can only speculate.



      But in general, you should avoid bit shifting on signed integer types, as that leads to various forms of poorly-defined behavior. This in turn means that you have to be careful with small integer types too, because they get promoted to signed int. See Implicit type promotion rules.



      The specific case of (uint8)((variable >> 8) & 0xFFu); is safe if variable is unsigned. Otherwise it is unsafe, since right-shifting a negative value leads to implementation-defined behavior (arithmetic or logical shift).



      variable << 8 will invoke undefined behavior on 16 bit systems in case variable is a small integer type, or an int16_t.



      The safest, most portable way no matter left/right shift is therefore this:



      chunk_lsb = variable;
      chunk_msb = ((unsigned int)variable >> 8);


      Though you might want to be overly explicit in order to silence all compiler warnings:



      chunk_lsb = (uint8_t) (variable & 0xFFu);
      chunk_msb = (uint8_t) ( (unsigned int)variable>>8 & 0xFFu );





      share|improve this answer




























        3














        It isn't clear what type variable is. Without that specified, we can only speculate.



        But in general, you should avoid bit shifting on signed integer types, as that leads to various forms of poorly-defined behavior. This in turn means that you have to be careful with small integer types too, because they get promoted to signed int. See Implicit type promotion rules.



        The specific case of (uint8)((variable >> 8) & 0xFFu); is safe if variable is unsigned. Otherwise it is unsafe, since right-shifting a negative value leads to implementation-defined behavior (arithmetic or logical shift).



        variable << 8 will invoke undefined behavior on 16 bit systems in case variable is a small integer type, or an int16_t.



        The safest, most portable way no matter left/right shift is therefore this:



        chunk_lsb = variable;
        chunk_msb = ((unsigned int)variable >> 8);


        Though you might want to be overly explicit in order to silence all compiler warnings:



        chunk_lsb = (uint8_t) (variable & 0xFFu);
        chunk_msb = (uint8_t) ( (unsigned int)variable>>8 & 0xFFu );





        share|improve this answer


























          3












          3








          3







          It isn't clear what type variable is. Without that specified, we can only speculate.



          But in general, you should avoid bit shifting on signed integer types, as that leads to various forms of poorly-defined behavior. This in turn means that you have to be careful with small integer types too, because they get promoted to signed int. See Implicit type promotion rules.



          The specific case of (uint8)((variable >> 8) & 0xFFu); is safe if variable is unsigned. Otherwise it is unsafe, since right-shifting a negative value leads to implementation-defined behavior (arithmetic or logical shift).



          variable << 8 will invoke undefined behavior on 16 bit systems in case variable is a small integer type, or an int16_t.



          The safest, most portable way no matter left/right shift is therefore this:



          chunk_lsb = variable;
          chunk_msb = ((unsigned int)variable >> 8);


          Though you might want to be overly explicit in order to silence all compiler warnings:



          chunk_lsb = (uint8_t) (variable & 0xFFu);
          chunk_msb = (uint8_t) ( (unsigned int)variable>>8 & 0xFFu );





          share|improve this answer













          It isn't clear what type variable is. Without that specified, we can only speculate.



          But in general, you should avoid bit shifting on signed integer types, as that leads to various forms of poorly-defined behavior. This in turn means that you have to be careful with small integer types too, because they get promoted to signed int. See Implicit type promotion rules.



          The specific case of (uint8)((variable >> 8) & 0xFFu); is safe if variable is unsigned. Otherwise it is unsafe, since right-shifting a negative value leads to implementation-defined behavior (arithmetic or logical shift).



          variable << 8 will invoke undefined behavior on 16 bit systems in case variable is a small integer type, or an int16_t.



          The safest, most portable way no matter left/right shift is therefore this:



          chunk_lsb = variable;
          chunk_msb = ((unsigned int)variable >> 8);


          Though you might want to be overly explicit in order to silence all compiler warnings:



          chunk_lsb = (uint8_t) (variable & 0xFFu);
          chunk_msb = (uint8_t) ( (unsigned int)variable>>8 & 0xFFu );






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered 1 hour ago









          LundinLundin

          110k17161265




          110k17161265























              2














              If chunk_lsb is an 8 bit object, use cast or mask (not both). Useful in quieting pedantic warnings about range reduction. I prefer the mask - unless the compiler is picky.



              uint8_t chunk_lsb = (uint8_t) variable;
              // or
              uint8_t chunk_lsb = variable & 0xFFu;


              Otherwise use the mask.



              unsigned chunk_lsb = variable & 0xFFu;





              share|improve this answer




























                2














                If chunk_lsb is an 8 bit object, use cast or mask (not both). Useful in quieting pedantic warnings about range reduction. I prefer the mask - unless the compiler is picky.



                uint8_t chunk_lsb = (uint8_t) variable;
                // or
                uint8_t chunk_lsb = variable & 0xFFu;


                Otherwise use the mask.



                unsigned chunk_lsb = variable & 0xFFu;





                share|improve this answer


























                  2












                  2








                  2







                  If chunk_lsb is an 8 bit object, use cast or mask (not both). Useful in quieting pedantic warnings about range reduction. I prefer the mask - unless the compiler is picky.



                  uint8_t chunk_lsb = (uint8_t) variable;
                  // or
                  uint8_t chunk_lsb = variable & 0xFFu;


                  Otherwise use the mask.



                  unsigned chunk_lsb = variable & 0xFFu;





                  share|improve this answer













                  If chunk_lsb is an 8 bit object, use cast or mask (not both). Useful in quieting pedantic warnings about range reduction. I prefer the mask - unless the compiler is picky.



                  uint8_t chunk_lsb = (uint8_t) variable;
                  // or
                  uint8_t chunk_lsb = variable & 0xFFu;


                  Otherwise use the mask.



                  unsigned chunk_lsb = variable & 0xFFu;






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered 1 hour ago









                  chuxchux

                  83.2k872151




                  83.2k872151























                      -1















                      Maybe there's none and just use the cast to reduce calculations is the best way?




                      General speaking, the asm code will be the same, so in terms of speed, it does not matter which one you use:




                      • masking: https://godbolt.org/z/Olrw3x

                      • casting: https://godbolt.org/z/EEdvQZ



                      What do you guys think?




                      IMO, the first one is clearer, in terms of readability, but I cannot figure out a coding standard or guideline which supports my preference. Anyway, I would use a const variable if your preference is the second one, to remove magic numbers and make clearer that the purpose is masking (assuming that you have chosen a correct name for the const variable).






                      share|improve this answer



















                      • 1





                        Anyway, I would use a const variable if your preference is the second one, to remove magic numbers and make clearer that the purpose is masking Anyone who thinks 0xFF in the context of bit masking is a "magic number" that has to be papered over with a variable is engaging in cargo-cult programming. What possible variable can be more clear than 0xFF as a bit mask? one_byte_bit_mask_0xFF?

                        – Andrew Henle
                        1 hour ago













                      • IMO, if the purpose is to mask, the word mask is clearer than any (magic) number.

                        – Jose
                        1 hour ago











                      • IMO, if the purpose is to mask, the word mask is clearer than any (magic) number Oh? How many bits does this mask: unsigned int result = input & mask; And no, I didn't DV.

                        – Andrew Henle
                        1 hour ago













                      • 0xFF vs one_byte_bit_mask_0xFF vs mask, I choose the second one as the least-bad option.

                        – Jose
                        54 mins ago
















                      -1















                      Maybe there's none and just use the cast to reduce calculations is the best way?




                      General speaking, the asm code will be the same, so in terms of speed, it does not matter which one you use:




                      • masking: https://godbolt.org/z/Olrw3x

                      • casting: https://godbolt.org/z/EEdvQZ



                      What do you guys think?




                      IMO, the first one is clearer, in terms of readability, but I cannot figure out a coding standard or guideline which supports my preference. Anyway, I would use a const variable if your preference is the second one, to remove magic numbers and make clearer that the purpose is masking (assuming that you have chosen a correct name for the const variable).






                      share|improve this answer



















                      • 1





                        Anyway, I would use a const variable if your preference is the second one, to remove magic numbers and make clearer that the purpose is masking Anyone who thinks 0xFF in the context of bit masking is a "magic number" that has to be papered over with a variable is engaging in cargo-cult programming. What possible variable can be more clear than 0xFF as a bit mask? one_byte_bit_mask_0xFF?

                        – Andrew Henle
                        1 hour ago













                      • IMO, if the purpose is to mask, the word mask is clearer than any (magic) number.

                        – Jose
                        1 hour ago











                      • IMO, if the purpose is to mask, the word mask is clearer than any (magic) number Oh? How many bits does this mask: unsigned int result = input & mask; And no, I didn't DV.

                        – Andrew Henle
                        1 hour ago













                      • 0xFF vs one_byte_bit_mask_0xFF vs mask, I choose the second one as the least-bad option.

                        – Jose
                        54 mins ago














                      -1












                      -1








                      -1








                      Maybe there's none and just use the cast to reduce calculations is the best way?




                      General speaking, the asm code will be the same, so in terms of speed, it does not matter which one you use:




                      • masking: https://godbolt.org/z/Olrw3x

                      • casting: https://godbolt.org/z/EEdvQZ



                      What do you guys think?




                      IMO, the first one is clearer, in terms of readability, but I cannot figure out a coding standard or guideline which supports my preference. Anyway, I would use a const variable if your preference is the second one, to remove magic numbers and make clearer that the purpose is masking (assuming that you have chosen a correct name for the const variable).






                      share|improve this answer














                      Maybe there's none and just use the cast to reduce calculations is the best way?




                      General speaking, the asm code will be the same, so in terms of speed, it does not matter which one you use:




                      • masking: https://godbolt.org/z/Olrw3x

                      • casting: https://godbolt.org/z/EEdvQZ



                      What do you guys think?




                      IMO, the first one is clearer, in terms of readability, but I cannot figure out a coding standard or guideline which supports my preference. Anyway, I would use a const variable if your preference is the second one, to remove magic numbers and make clearer that the purpose is masking (assuming that you have chosen a correct name for the const variable).







                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered 2 hours ago









                      JoseJose

                      1,239415




                      1,239415








                      • 1





                        Anyway, I would use a const variable if your preference is the second one, to remove magic numbers and make clearer that the purpose is masking Anyone who thinks 0xFF in the context of bit masking is a "magic number" that has to be papered over with a variable is engaging in cargo-cult programming. What possible variable can be more clear than 0xFF as a bit mask? one_byte_bit_mask_0xFF?

                        – Andrew Henle
                        1 hour ago













                      • IMO, if the purpose is to mask, the word mask is clearer than any (magic) number.

                        – Jose
                        1 hour ago











                      • IMO, if the purpose is to mask, the word mask is clearer than any (magic) number Oh? How many bits does this mask: unsigned int result = input & mask; And no, I didn't DV.

                        – Andrew Henle
                        1 hour ago













                      • 0xFF vs one_byte_bit_mask_0xFF vs mask, I choose the second one as the least-bad option.

                        – Jose
                        54 mins ago














                      • 1





                        Anyway, I would use a const variable if your preference is the second one, to remove magic numbers and make clearer that the purpose is masking Anyone who thinks 0xFF in the context of bit masking is a "magic number" that has to be papered over with a variable is engaging in cargo-cult programming. What possible variable can be more clear than 0xFF as a bit mask? one_byte_bit_mask_0xFF?

                        – Andrew Henle
                        1 hour ago













                      • IMO, if the purpose is to mask, the word mask is clearer than any (magic) number.

                        – Jose
                        1 hour ago











                      • IMO, if the purpose is to mask, the word mask is clearer than any (magic) number Oh? How many bits does this mask: unsigned int result = input & mask; And no, I didn't DV.

                        – Andrew Henle
                        1 hour ago













                      • 0xFF vs one_byte_bit_mask_0xFF vs mask, I choose the second one as the least-bad option.

                        – Jose
                        54 mins ago








                      1




                      1





                      Anyway, I would use a const variable if your preference is the second one, to remove magic numbers and make clearer that the purpose is masking Anyone who thinks 0xFF in the context of bit masking is a "magic number" that has to be papered over with a variable is engaging in cargo-cult programming. What possible variable can be more clear than 0xFF as a bit mask? one_byte_bit_mask_0xFF?

                      – Andrew Henle
                      1 hour ago







                      Anyway, I would use a const variable if your preference is the second one, to remove magic numbers and make clearer that the purpose is masking Anyone who thinks 0xFF in the context of bit masking is a "magic number" that has to be papered over with a variable is engaging in cargo-cult programming. What possible variable can be more clear than 0xFF as a bit mask? one_byte_bit_mask_0xFF?

                      – Andrew Henle
                      1 hour ago















                      IMO, if the purpose is to mask, the word mask is clearer than any (magic) number.

                      – Jose
                      1 hour ago





                      IMO, if the purpose is to mask, the word mask is clearer than any (magic) number.

                      – Jose
                      1 hour ago













                      IMO, if the purpose is to mask, the word mask is clearer than any (magic) number Oh? How many bits does this mask: unsigned int result = input & mask; And no, I didn't DV.

                      – Andrew Henle
                      1 hour ago







                      IMO, if the purpose is to mask, the word mask is clearer than any (magic) number Oh? How many bits does this mask: unsigned int result = input & mask; And no, I didn't DV.

                      – Andrew Henle
                      1 hour ago















                      0xFF vs one_byte_bit_mask_0xFF vs mask, I choose the second one as the least-bad option.

                      – Jose
                      54 mins ago





                      0xFF vs one_byte_bit_mask_0xFF vs mask, I choose the second one as the least-bad option.

                      – Jose
                      54 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%2f54866461%2fshould-a-cast-be-used-to-truncate-a-long-variable%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

                      Szabolcs (Ungheria) Altri progetti | Menu di navigazione48°10′14.56″N 21°29′33.14″E /...

                      Discografia di Klaus Schulze Indice Album in studio | Album dal vivo | Singoli | Antologie | Colonne...

                      How to make inet_server_addr() return localhost in spite of ::1/128RETURN NEXT in Postgres FunctionConnect to...