Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

[C++] Similar method of bitconverter -- ToInt16

  1. Dec 15, 2014 #1
    In C#,
    byte[] tail={.....}
    short reader = BitConverter.ToInt16(tail, 4);
    which is to convert 2 bytes 4 and 5 to a short value.
    I'd like to do this in C++
    So I do

    char tail[]={...}
    short reader=toInt16(tail,4);
    short toInt16(char*tail,int index)
        int n=index;
        int m=n+1;
        string s(tail[n]);
        return atoi(s.c_str());
    but this is not correct. there is not method to export a short, I consider also the system type (big/little endian) my code must run on. Any help please ... :)
  2. jcsd
  3. Dec 15, 2014 #2
    Your "tail" bytes are binary, not ASCII. So atoi is the wrong function to use.
    In order to address the big/little-endian issue, you will need to write two functions. I would suggest you create a "BIGENDIAN" definition.

    Code (Text):

    short toInt16(char *tail, int index)
    #if defined(BIGENDIAN)
      return (short)( ((unsigned short)(tail[index])<<8)+(unsigned char)(tail[index+1]) );
      return (short)( ((unsigned short)(tail[index+1])<<8)+(unsigned char)(tail[index]) );
    1) Check out the function htons().
    2) Do you want to check you input parameters "tail" and "index" for validity before using them in the function?
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook