Last active
August 29, 2015 14:19
-
-
Save meki/797b09b901d2a2df677a to your computer and use it in GitHub Desktop.
Byte <--> Ushort, Short Converter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) ); | |
} | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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