Skip to content

Instantly share code, notes, and snippets.

@meki
Last active August 29, 2015 14:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save meki/797b09b901d2a2df677a to your computer and use it in GitHub Desktop.
Save meki/797b09b901d2a2df677a to your computer and use it in GitHub Desktop.
Byte <--> Ushort, Short Converter
struct Converter
{
static unsigned short UShort(unsigned char b1, unsigned char b2)
{
return (unsigned short)( (0xff00 & (b2 << 8)) | (0x00ff & (b1 << 0)) );
}
static short Short(unsigned char b1, unsigned char b2)
{
return (short)( (0xff00 & (b2 << 8)) | (0x00ff & (b1 << 0)) );
}
};
#include <iostream>
#include "Converter.h"
using namespace std;
int main(void){
{
short val = -32767;
unsigned char* low = reinterpret_cast<unsigned char*>(&val);
unsigned char* high = low + 1;
cout << Converter::UShort(*low, *high) << endl;
}
{
unsigned short val = 45566;
unsigned char* low = reinterpret_cast<unsigned char*>(&val);
unsigned char* high = low + 1;
cout << Converter::UShort(*low, *high) << endl;
}
{
short val = -32767;
unsigned char* low = reinterpret_cast<unsigned char*>(&val);
unsigned char* high = low + 1;
cout << Converter::Short(*low, *high) << endl;
}
{
unsigned short val = 45566;
unsigned char* low = reinterpret_cast<unsigned char*>(&val);
unsigned char* high = low + 1;
cout << Converter::Short(*low, *high) << endl;
}
unsigned short val = 124;
val -= 32768;
cout << val << endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment