How to convert a short into 2 chars.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • AmmarN
    New Member
    • Mar 2007
    • 18

    How to convert a short into 2 chars.

    I would like to convert a short in to 2 chars. Since short is 2 bytes i would like to isolate them and convert them into 2 chars.

    Any suggestions would be appreciated.
    Thanks in advance.
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    You will need to use the bitwise and shift operators.

    Comment

    • AmmarN
      New Member
      • Mar 2007
      • 18

      #3
      Originally posted by Banfa
      You will need to use the bitwise and shift operators.
      Thanks for your reply. I know thats what I need to use but i dont know how.
      I would really appreciate if you could explain that.
      Thanks.

      Comment

      • Banfa
        Recognized Expert Expert
        • Feb 2006
        • 9067

        #4
        you use the shift operator to position the bits you require into the locations you require them in and then you use the bitwise AND operator to isolate those bits so you can assign them to a char variable.

        Comment

        • AmmarN
          New Member
          • Mar 2007
          • 18

          #5
          Originally posted by Banfa
          you use the shift operator to position the bits you require into the locations you require them in and then you use the bitwise AND operator to isolate those bits so you can assign them to a char variable.

          Thank you very much for your help.i got it figured out.I will post my solution here anyways just incase some one else looks for it in the future.

          short value = (some value);
          char a;
          char b;

          a=value; // to copy the first 8 bits.
          value = value>>8; //push the other 8 bits to the right
          b=value;

          Comment

          • drnrusu
            New Member
            • Sep 2007
            • 6

            #6
            Originally posted by AmmarN
            Thank you very much for your help.i got it figured out.I will post my solution here anyways just incase some one else looks for it in the future.

            short value = (some value);
            char a;
            char b;

            a=value; // to copy the first 8 bits.
            value = value>>8; //push the other 8 bits to the right
            b=value;
            Thanks for solution I needed some time ago
            Anyway thanks again

            Comment

            • jackmejia
              New Member
              • Aug 2007
              • 5

              #7
              I am dealing with this same problem, but I get the solution from another way not sure how secure it is.

              clen = new char[2];
              *(unsigned short *)clen = m_length;

              Comment

              Working...