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

  • C/C++
  • Thread starter Silicon Waffle
  • Start date
  • Tags
  • #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 ... :)
Technology news on Phys.org
  • #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.

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?
  • Like
Likes Silicon Waffle and jim mcnamara

1. What is the purpose of the ToInt16 method in C++?

The ToInt16 method in C++ is used to convert a given data type to a 16-bit integer (short) value. It is often used in conjunction with the BitConverter class to perform data type conversion.

2. How does the ToInt16 method differ from other similar methods in C++?

Unlike other similar methods in C++, such as ToInt32 and ToInt64, the ToInt16 method specifically converts a data type to a 16-bit integer value. This can be useful when working with data that requires a smaller range of values.

3. What data types can be converted using the ToInt16 method?

The ToInt16 method can be used to convert any data type that can be represented by a 16-bit integer value, such as char, short, and unsigned short.

4. Can the ToInt16 method handle conversion of big-endian and little-endian data?

Yes, the ToInt16 method can handle conversion of data from both big-endian and little-endian formats. It uses the endianness of the system to determine how the data should be converted.

5. When should I use the ToInt16 method in my C++ code?

The ToInt16 method is useful when you need to convert a data type to a 16-bit integer value, for example when working with binary data or when dealing with data that has a limited range of values. It can also be used for interoperability with other systems that use 16-bit integers.

Suggested for: [C++] Similar method of bitconverter -- ToInt16