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

  • Context: C/C++ 
  • Thread starter Thread starter Silicon Waffle
  • Start date Start date
  • Tags Tags
    Method
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
1 reply · 6K views
Silicon Waffle
Messages
160
Reaction score
202
In C#,
PHP:
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
PHP:
char tail[]={...}
short reader=toInt16(tail,4);
...
short toInt16(char*tail,int index)
{
    int n=index;
    int m=n+1;
    string s(tail[n]);
    s+=tail[m];
    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 ... :)
 
Physics news on Phys.org
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:
short toInt16(char *tail, int index)
{
#if defined(BIGENDIAN)
  return (short)( ((unsigned short)(tail[index])<<8)+(unsigned char)(tail[index+1]) );
#else
  return (short)( ((unsigned short)(tail[index+1])<<8)+(unsigned char)(tail[index]) );
#endif
}
Also:
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?
 
  • Like
Likes   Reactions: Silicon Waffle and jim mcnamara