Title: converting char to int
Description: i had a use for this belivie it or not
ih8censorship - September 25, 2003 12:21 AM (GMT)
ok recently i needed to convert a char to an int. i searched throguh my book and learned of static cast here is a little example of it:
| CODE |
char letter;
int main() { cin>>letter; int x=static_cast<int>(letter) cout<<x; Sleep(10000); return 0; } |
that code may not work exactly right but you get the idea. the number returned from static_cast is the acsii value of it or something im not exactly sure how it works i just know that it does ;)
Dragon - September 25, 2003 01:10 AM (GMT)
You can just do this:
| CODE |
#include <iostream.h>
int main() { char i[100]; cout<<"Enter a value for i: "; cin>>i; cout<<(int)i<<endl; system("pause"); } |
I haven't tested the code, but it should work.
ih8censorship - September 25, 2003 01:17 AM (GMT)
well dragon, yours gives me a number value too, but it isnt the ascii value for it. try my code with the letter f inputted. you should get 102. then when the letter f is inputted in your program you get 7798128. i have no idea why.i think its because your trying to convert a pointer to an int, (just the array name without an element number is basicly a pointer i guess)
Dragon - September 25, 2003 01:25 AM (GMT)
Try this:
| CODE |
#include <iostream.h>
int main() { char i; cout<<"Enter value for i: "<<endl; cin>>i; cout<<(int)i<<endl; system("pause"); } |
ih8censorship - September 25, 2003 01:30 AM (GMT)
yep that works i knew it was something to do with having only the array name and not the element too. i also tryed having a array with the element and that works like it is supposed to too.
TheHawgMaster - September 25, 2003 01:03 PM (GMT)
A single char can just hold a number up to 2^8 (256). This is obviously no problem to the compiler and it will do the cast implicitly since an int can (usually) hold up to 2^32.
myork - January 27, 2004 07:46 PM (GMT)
The C cast is now considered very bad form an should be avoided like the plague. The reason behind it is that porting code between platforms becomes very tricky if a program has made too many assumptions about the underlying types and tracking down a bug becomes seriously difficult.
C++ has introduced 4 new cast operators.
1) reinterpret_cast<X>(val)
2) dynamic_cast<X>(val)
4) static_cast<X>(val)
5) const_cast<X>(val)
The first advantage is that these are east to find in the code (just search for '_cast'). The second advantage is that the cast actually perform some checking on the input data:
Compile Time casts.
=============
const_cast<X>(val)
used to add/remove constness from a type.
reinterpret_cast<X>(val)
This converts any type to any type. No checking is done. This is not really portable between platforms and each compiler manufacturer is free to implement it as they see fit. Generally the underlying bit pattern will remain the same and the type will change.
Run Time casts.
==========
static_cast<X>(val)
used to convert related types.
| CODE |
Examples: int -> float. char-> int
void* -> int*
|
dynamic_cast<X>(val)
used to convert the type up/down the inheritance chain. It will return NULL if casting a pointer to an unrelated pointer. Will throw an exception if casting a type.
| CODE |
Example: class Base {public: virtual ~Base() {}}; class A: public Base {}; class B: public Base {}; class B1: public B {};
A a; B1 b;
Base* base = dynamic_cast<Base*>(&A); B1* b1P = dynamic_cast<B1*>(base); // Returns NULL because base is pointing at an object of type A which is not the same as a B1. B1* b1P2 = &b;
|
NB. dynamic_cast<X>() uses the 'run time type information' (RTTI). Some compilers don't generate this by default and you will need to turn it on.
People somtimes argue that dynamic_cast<X>() is too much overhead and returns the same value as is passed into it. Thus it is easier to use the more dangarus reinterpret_cast<X>(). This is dangerous and not true. If you only use single inheritance then the value returned by dynamic_cast<X>() probably has the same bit pattern as the input, but this is compiler specific and depends on the ABI. If you use multiple inheritance then the value returned probably does not have the same underlying bit pattern (but again that will depend on the ABI).
| CODE |
class X {public: virtual ~X() {} int xValue;}; class Y {public: virtual ~Y() {} int yValue;}; class Z: public X,Y { }
Z zValue; Z* zPointer = &zValue;
X* xPointer = dynamic_cast<X*>(zPointer); Y* yPointer = dynamic_cast<Y*>(yPointer);
|
xPointer and yPointer probably do not point at the same memory location.
FrozenKnight - January 28, 2004 11:37 AM (GMT)
LoL, All that trouble just to change they type of a var. I have found typecasting to be quite useful in the past but this topic looks useful. Especially in cases where multiple casts are required for simple operations, like cases where you need to turn a pointer into an int (debugging), or those darn double's that I’ve seen people using in any GM compatible code. Who ever though up using a double for returning a value anyway? (Too much overhead for my taste.)
myork - January 28, 2004 02:51 PM (GMT)
| QUOTE |
| LoL, All that trouble just to change they type of a var. |
I hope you are being sarcastic.
One of the major advantages of C++ over C is type safty. Once you start to ignore types your program becomes unportable (which is good for Microsoft as most new users are windows people).
Good type safty (or from the language perspective type strictness) is an essential part of most modern languages. The C cast operator throws all the type information away and that is why it is now considered very bad programing (its the goto of the modern languages).
| QUOTE |
| cases where you need to turn a pointer into an int (debugging) |
I am not sure why you want to turn a pointer into an int even for debugging.
In C:
| CODE |
| frpitnf(stdout,"A pointer value: %p\n",myPointer); |
In C++
| CODE |
| std::cout << "A pointer value: " << myPointer << "\n"; |
In C programming you were somtimes forced to convert pointers into void* to pass them to libraries that provided callback data, but C++ has much more sophisticated ways of doing things and this practice has been made obsolete (unless you are using older C libs).
FrozenKnight - January 29, 2004 09:22 AM (GMT)
Var types aren’t all that necessary, and sometimes can be an annoyance. Your computer treats all var types the same except floats or very large numbers. i know this because i am currently studying ASM programing and i am having some trouble with floats. i also don’t understand how your code can become unportable with a standardized function. (oh and btw, who cares if the code you compiled on your windows computer wont compile on an linux or mac PC. most programs are OS specific anyway.) over this last year (since i started looking at programmer forums) i've learned that portability isn’t as far stretched as people think. probably the most portable language is ASM because it is hardware specific and not software dependant. the illusion of portability is created by programmers that use similar software and think similarly. if you were to hand a perfectly standards compliant 100 page program over to a programmer who just finished a C++ class and asked him to go over it. not only would he probably get lost in it it most likely wouldn’t even compile on his compiler. true portability only exists in code segments and even then you have to be careful.
dr voodoo - January 29, 2004 12:16 PM (GMT)
| QUOTE |
| probably the most portable language is ASM because it is hardware specific and not software dependant. |
It's nearly impossible to write a prog without OS interaction (kernel32.ExitProces + message loop).
Also lots of C++ code is not very protable but that's because the programmer has made assumations about the underlaying hardware. A well written no GUI prog is protable.
FrozenKnight - January 29, 2004 01:02 PM (GMT)
Sorry Voodoo, your right. i was referring mostly to the way it translates. the message loop is based inside your program weather it's asm or C/C++. but you do need to make calls to the kernel for any OS interactions. what i was referring to with too much haste was the fact that in C/C++ you are relying on another programmers code to do most of the work for you. in asm you do most of the work your self and only have to rely on external code for OS interaction unless you specify otherwise. in C and C++ the compiled code may be standardized, but they left the actually coding to the programmers of the compilers. i've never seen nor herd of required ways to do C/C++ functions in asm. all the specifications specify is how the functions/keywords are supposed to act. asm things are different the code always assembles the same no matter which assembler you use. there may be a few differences as to which op codes an assembler accepts and there may be differences in the way comments and certain macros are done. but if translated correctly it will always work the same. but you are forces to code OS specific. but a good coder can place detections into his program and make the program cross platform even going as far as creating a program that runs through windows GUI and dos text/GUI and the really good asm programmers can even go as far as to write their programs to run on almost all known OS and still be one file (size and complexity increases though) and it's often not worth the effort but it can still be done
myork - January 29, 2004 05:01 PM (GMT)
About portability.
I write programs that are designed to be portable. My code has GUI's and runs on Win/Mac/Unix/Linux etc, infact my current project has too support 25 different platforms (of which 4 are Windows based). One of the most important parts of my work is to make sure the code is portable. Portability is not an illusion it is a fact it just takes though (and a bit of skill :P ). You can not assume anything about the underlying hardware.
ASM is not portable.
It works on 1 type of hardware. If you want to do anything portable you need to use a high level language and let the compiler do the work of generating the optimum assembly for a given hardware.
If you want a tight fully optimised loop then ASM may be the way to go, but 99 times out of 100 the compiler will do it better than you can do it. I know from experience. We had a team of asm programmers developing optimum ways of doing somthing on a given hardware, the compiler was then constantly updated from their findings. As a result our compiler could generally beat any hand written program that performed the same task (NB This was a C compiler so it did not add the extra bloat of C++).
About the only thing ASM is really good for is writting hardware specific drivers, or the 1% of cases where the compiler can not optimise the code because of a percieved dependency that can not be confirmed to be false.
FrozenKnight - January 30, 2004 01:50 PM (GMT)
I’ve only found a few cases where the compiler can beat me in fact the compiler generally generate 1.5x the opcodes I do. Sometimes the compiler code is faster but I’ve found that I can learn from what the compiler is doing.
About asm portability most hardware is being created so that it is backwards compatible (ie: can do everything the previous model can do). and if you take your asm code over to a assembler designed for another computer it will generate compatible code. because asm works the same way on all processors as long as all the same functions are supported. (Like taking a 32 bit program over to a 16 bit system.)
But as with everything that gets programmed you still have to rely on the programmer for any kind of portability. Portability isn’t the holy grail of programming it's just a guideline by which you have the option of following. The real question is will your program be useable 10 years from now. I know some asm programs written back in the early 90's still work today. But I can’t say the same for their compiled counterparts, because some of the compiled counterparts relied on extra software that is no longer available. C++ may never suffer from this disadvantage but it is something to think about when you program relying on libraries like MFC. the windows kernel will probably be around for a while so your probably safe there for now but I doubt it will be the same 10-20 years from now, which is the real test of portability.
My opinion is program so that your program relies on as little as possible. That way you reduce the chances that something you just spent the better part of a year working on wont stop working tomorrow.
myork - January 30, 2004 03:42 PM (GMT)
FK. Complete hogwash.
| QUOTE |
| I’ve only found a few cases where the compiler can beat me in fact the compiler generally generate 1.5x the opcodes I do. Sometimes the compiler code is faster but I’ve found that I can learn from what the compiler is doing. |
I have noticed that compilers have switches that allow it to optimise for speed or space. Try switching your compiler to optimise for space and I would put money on it beating you for size for all but the most trivial programs. I have been building compilers for a while and I found even the most experienced ASM writters (with 20+ yeares of experience) find it hard to consistantly write better bug free code than than the compiler.
| QUOTE |
| About asm portability most hardware is being created so that it is backwards compatible (ie: can do everything the previous model can do). and if you take your asm code over to a assembler designed for another computer it will generate compatible code. |
Only if you stay in the same family.
Pentium ASM will not work on PPC, MIPS, Sparc, Tru-64 (and those are just the common ones).
Also If you move your code to a 64 bit version of the processor your code is now no-longer optimal. This is what the compiler does it provides hardware neutrality.
| QUOTE |
| But as with everything that gets programmed you still have to rely on the programmer for any kind of portability. Portability isn’t the holy grail of programming it's just a guideline by which you have the option of following. |
Yes the responcability is on the programmer, but this is generally because of language shortcomings. If the language had been designed better portability would have been a smaller issue. Java being a good example of a very portable language.
| QUOTE |
| The real question is will your program be useable 10 years from now. I know some asm programs written back in the early 90's still work today. But I can’t say the same for their compiled counterparts, because some of the compiled counterparts relied on extra software that is no longer available. |
Now you are comparing apples to oranges.
Any program the depends on another library is dependant on that library it does not matter if the program is written in C++ or ASM. I still have C program I wrote back in the 80's that still work on all platforms. I have BASIC programs I wrote int the early 80's that still work (even after you compile them). I have ASM code (chess) written in the 70's that will only works on 1 platform (A Sinclair ZX Spectrum [Which has a Z-80(A) 8 bit processor]) and there is no way I could port it too a new processor.
If a C++ program is dependant on the windows libraries to generate a window then the same ASM program is also dependant on the windows library. As long as you stick to standard libraries your code will have a long life.
| QUOTE |
| the windows kernel will probably be around for a while so your probably safe there for now but I doubt it will be the same 10-20 years from now, which is the real test of portability. |
The windows kernal may not be the same, but for a C++ program who cares. The C++ program is linked against the standard libraries not the kernal. The Kernal will be built against the standard libraries and everything will work.
If a C++ program is using a kernal call to accomplish a specific task then your ASM program will also have to use the kernal calls and as a result both programs will be tied to the availability of that kernall call.
Short of a device driveror embedded systems. I can not think a case where writting in ASM will make you better off.
C++ code is:
1) More portable.
2) Will automatically be optimised for the current platform.
3) Will be more maintainable.
4) Will be more future proffed then ASM.
Disadvantages of C++
1) It adds lots of extra code to protect you from bugs. Thus increasing the size of your program. If size is important use C.
2) It is not as good in time critical code. Use C to compensate. If you still need the extra speed then look at ASM, but don't bet on it helping.
ASM code advantages:
1) Can be more effecient if you have the experience.
2) or can be more compact if you have the experience.
Ok. Thats my rant. Maybee we should talk this verbal spar to another forum I am sure the others are getting board of the "my language is better than yours argument".
FrozenKnight - January 31, 2004 02:33 PM (GMT)
myork sounds like your on a holy war agents non portability.
I was just stating that portability isn't always a good thing. just because your program isn't portable doesn't mean that it isn't good. it's almost imposable to make a portable optimized program. so the general idea is that if you want speed go system specific, but if you want system independence then go portable.
and if you assemble your program with a windows assembler then it's going to run on windows. if you assemble it with a mac assembler then it will run on a mac. the hex codes may be different but they still do the same thing. you just have to use a assembler that converts to the hex codes for the processor you are using.
and as a reply to your optimized compiler statement. compilers are only able to work within the scope which they were programmed for a good human mind can surpass that. (i'm sure you've heard the term "think out of the box") as the programmer you understand what you want your program to do a compiler doesn’t it just sees that this algorithm will work better here or that will work better there. the human mind is a marvelous item and i still believe that it has more power than any compiler will ever manage to acquire. the way i see it, if a compiler can do something better than me i can always disassemble what the compiler is doing then 'cut out the fat' and usually surpass it. and yes even an optimized compiler does unnecessary things.
nickeax - July 8, 2004 02:29 AM (GMT)
| QUOTE |
and if you assemble your program with a windows assembler then it's going to run on windows. if you assemble it with a mac assembler then it will run on a mac. the hex codes may be different but they still do the same thing. you just have to use a assembler that converts to the hex codes for the processor you are using.
|
Well that's not correct... I think you need to read a good book about ASM. The 'HEX Codes' you refer to actually expand into binary numbers that represent the values placed on the pins of your CPU (or the device that prepares the instruction for the CPU). Those 'HEX Codes' are very specific to the machine, they represent things a particular famliy of CPUs can do. CPUs from different familys will not be able to execute the same instructions.
The assembler may have it's own assembler specific keywords or directives, but they usually only serve to aid in allocation of memory, macros or typdefs. At the heart of your program will be machine instructions.
Each line of an assembly program is one machine instruction, unless there is some other assembler stuff there, but you know what I mean.
The assembler does not decide what to do with each instruction. It simply builds a machine instruction based on the class of the instruction and the operands(if any). A machine instruction is a variably wide string of bits that contains packed data. The whole string of bits contains sub strings that will contain the various operands and or memory addresses.
To assemble asm on different cpu families requires a conversion process of the actual source code. Then, you could assemble the new source code. Even then, you may be using instructions that only exist for a particular CPU. I think you mis-understood the difference between a compiler and an assembler, but I hope I cleared that up!
Nick.
Incubator - July 8, 2004 09:49 AM (GMT)
well, myork has a point there.
Writing portable programs is a good thing to do. I try to do this mysels but even s must admit my coding isnt very portable yet. (I still use way too much C casts)
The Only thing that can be called portable in any of my programs is the toolkit I use.
Qt and wxWindows. But thats as far as it goes. Thanks to myorks info I now know how to imptrove it. And if htere is a complete document explaining all the aspects of writing portable code then I would love to read that :)
ps: sorry for my crappy spelling, I can barelt see what I type
KTC - July 10, 2004 12:05 AM (GMT)
Here we go again.... :rolleyes:
AcidGame - July 10, 2004 05:35 PM (GMT)
just use atoi.. -_-
| CODE |
int moo; char mo; mo="29" moo=atoi(mo); cout << moo << endl;
|
something like that.
C-Saw - July 15, 2004 01:39 PM (GMT)
I was thinking, but couldn't you just do this:
| CODE |
char character = 'A'; int character2; character2 = character |
Heres a nice example:
| CODE |
#include <iostream> #include <cstdlib>
int main() { char character;
int character_code;
cout << "Type one character: ";
cin >> character;
cout << "You typed: " << character << endl;
character_code = character;
cout << character << "'s character code is: " << character_code << endl;
system("PAUSE");
return 0; } |
C-Man - July 15, 2004 02:00 PM (GMT)
only 1 problem there it's not A but 'A'
C-Saw - July 15, 2004 02:20 PM (GMT)