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

  • Context: C/C++ 
  • Thread starter Thread starter Silicon Waffle
  • Start date Start date
  • Tags Tags
    Method
Click For Summary
SUMMARY

The discussion focuses on converting a byte array to a short value in C++ using a custom function similar to C#'s BitConverter.ToInt16. The provided solution addresses the big/little-endian issue by defining a macro for endianess and implementing a conditional return based on it. The initial approach using atoi was incorrect due to the binary nature of the data. The final implementation ensures proper conversion by shifting and combining the byte values correctly.

PREREQUISITES
  • Understanding of C++ data types and memory representation
  • Knowledge of byte ordering (big-endian vs little-endian)
  • Familiarity with C++ preprocessor directives
  • Basic understanding of function parameter validation
NEXT STEPS
  • Research C++ preprocessor directives for conditional compilation
  • Learn about the htons() function and its applications
  • Explore techniques for validating function parameters in C++
  • Investigate other methods for byte manipulation in C++
USEFUL FOR

C++ developers, software engineers working with low-level data manipulation, and anyone dealing with binary data conversion and endianess issues.

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

Similar threads

Replies
1
Views
2K
Replies
5
Views
2K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 22 ·
Replies
22
Views
4K
  • · Replies 4 ·
Replies
4
Views
1K
Replies
89
Views
6K
  • · Replies 25 ·
Replies
25
Views
3K
Replies
73
Views
6K
  • · Replies 17 ·
Replies
17
Views
3K
  • · Replies 9 ·
Replies
9
Views
2K