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

  • #1
156
203

Main Question or Discussion Point

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 ... :)
 

Answers and Replies

  • #2
.Scott
Homework Helper
2,469
865
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?
 

Related Threads on [C++] Similar method of bitconverter -- ToInt16

Replies
7
Views
2K
Replies
0
Views
547
Replies
0
Views
1K
Replies
20
Views
1K
Replies
3
Views
1K
  • Last Post
Replies
0
Views
4K
  • Last Post
Replies
3
Views
5K
Replies
2
Views
1K
  • Last Post
Replies
0
Views
5K
Top