Friday, June 3, 2011

C++ Casting

I wrote a little demo to better describe casting to someone on a programming forum, and I thought it was pretty informative so here it is:

[code]
#include <iostream>
#include <limits>
#include <bitset>
#include <cassert>
#include <string>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
assert(sizeof(short) == 2);
assert(sizeof(signed char) == 1);

string bigBitString =
"0111111100000000";
string smallBitString =
"00000000";

bitset<16> big;
bitset<8> small;

for(string::size_type i = 0; i < bigBitString.size(); i++)
{
     big[i] = bigBitString[i] ==
'1' ? 1 : 0;
}


for(string::size_type i = 0; i < smallBitString.size(); i++)
{
     small[i] = smallBitString[i] ==
'1' ? 1 : 0;
}

short sBig = (short)big.to_ulong();
signed char cSmall = (signed char)small.to_ulong();

cout <<
"Sizeof short: " << sizeof(short) << endl;
cout <<
"Sizeof signed char: " << sizeof(signed char) << endl;
cout <<
"Short bits: " << big.to_string() << endl;
cout <<
"Signed char bits: " << small.to_string() << endl;

signed char casted = (signed char) big.to_ulong();

bitset<8> castedBits(casted);

cout <<
"Signed char bits after down-casting: " << castedBits.to_string() << endl;

cin.get();
return 0;
}
[/code]

I also wrote a small C++ string class demo, if you don't know what C++ strings are, you should definitely play around with this:

[code]
#include <iostream>
#include <string>
#include <algorithm>
#include <sstream>
using namespace std;

int main()
{

string cppString = "Hello World.";
cppString = "No error, no confusing C functions.";
getline(cin,cppString);//No buffer overflow from too much input.

//Use much like an array.
for( std::string::size_type i = 0; i < cppString.size(); i++ )
cppString[i] = 'x';

cppString += " -- Simple string concatenation too.";

//Usable with the C++ STL algorithms.
random_shuffle(cppString.begin(), cppString.end());

cout << "Can still get a C string if you REALLY want to also." 
<< endl << cppString.c_str() << endl;

//Easily convert from string to int/floating point type.
int someInt = 0;
cin >> cppString;
if((stringstream(cppString) >> someInt).fail())
cout << "Invalid number, woops!";
else
cout << someInt << endl << "Just your lucky number." << endl;
}
[/code]

13 comments:

  1. I got lost at the first line, haha!

    ReplyDelete
  2. I totally understood that....nah not really, I just getting into coding. Looking forward to what you got planned.

    ReplyDelete
  3. i'm green in programming like this text haha

    ReplyDelete
  4. Awesome post man! great blog!

    ReplyDelete
  5. I forgot I knew any C++. Don't remember much but it might come back.

    ReplyDelete
  6. I tried learning Java, man was it confusing!

    Keep up the great post!

    ReplyDelete
  7. i didn't understood anything !

    ReplyDelete
  8. Thanks, this is very informative.

    ReplyDelete