CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Jul 2010
    Posts
    10

    2's compliment conversion

    Hi
    I have 3 bytes of data that I am told represent a 24 bit integer. I am also told that the the data is in 2's compliment.
    How do i covert the bytes to an integer value

    Thanks for your time

  2. #2
    Join Date
    May 2001
    Location
    Germany
    Posts
    1,158

    Re: 2's compliment conversion


  3. #3
    Join Date
    Oct 2006
    Location
    Sweden
    Posts
    3,654

    Re: 2's compliment conversion

    Code:
    unsigned char data[3];
    int result = ((data[0] << 24) + (data[1] << 16) + (data[2] << 8)) >> 8;
    Assuming the data is big-endian and that int is 32 bits on your platform. The last shift is to sign extend the result.
    Debugging is twice as hard as writing the code in the first place.
    Therefore, if you write the code as cleverly as possible, you are, by
    definition, not smart enough to debug it.
    - Brian W. Kernighan

    To enhance your chance's of getting an answer be sure to read
    http://www.codeguru.com/forum/announ...nouncementid=6
    and http://www.codeguru.com/forum/showthread.php?t=366302 before posting

    Refresh your memory on formatting tags here
    http://www.codeguru.com/forum/misc.php?do=bbcode

    Get your free MS compiler here
    https://visualstudio.microsoft.com/vs

  4. #4
    Join Date
    Jul 2010
    Posts
    10

    Re: 2's compliment conversion

    Thanks!!!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured