Contents 1 Language comparison 1.1 C-like languages 1.1.1 Implicit type conversion 1.1.1.1 Type promotion 1.1.2 Explicit type conversion 1.2 C# and C++ 1.3 Eiffel 1.3.1 Definition of type conversion in Eiffel 1.3.2 Example 2 Security issues 3 See also 4 References 5 External links


Language comparison[edit] C-like languages[edit] Implicit type conversion[edit] Implicit type conversion, also known as coercion, is an automatic type conversion by the compiler. Some programming languages allow compilers to provide coercion; others require it. In a mixed-type expression, data of one or more subtypes can be converted to a supertype as needed at runtime so that the program will run correctly. For example, the following is legal C language code: double d; long l; int i; if (d > i) d = i; if (i > l) l = i; if (d == l) d *= 2; Although d, l and i belong to different data types, they will be automatically converted to equal data types each time a comparison or assignment is executed. This behavior should be used with caution, as unintended consequences can arise. Data can be lost when converting representations from floating-point to integer, as the fractional components of the floating-point values will be truncated (rounded toward zero). Conversely, precision can be lost when converting representations from integer to floating-point, since a floating-point type may be unable to exactly represent an integer type. For example, float might be an IEEE 754 single precision type, which cannot represent the integer 16777217 exactly, while a 32-bit integer type can. This can lead to unintuitive behavior, as demonstrated by the following code: #include <stdio.h> int main(void) { int i_value = 16777217; float f_value = 16777216.0; printf("The integer is: %d\n", i_value); printf("The float is: %f\n", f_value); printf("Their equality: %d\n", i_value == f_value); } On compilers that implement floats as IEEE single precision, and ints as at least 32 bits, this code will give this peculiar print-out: The integer is: 16777217 The float is: 16777216.000000 Their equality: 1 Note that 1 represents equality in the last line above. This odd behavior is caused by an implicit conversion of i_value to float when it is compared with f_value. The conversion causes loss of precision, which makes the values equal before the comparison. Important takeaways: float to int causes truncation, i.e., removal of the fractional part. double to float causes rounding of digit. long to int causes dropping of excess higher order bits. Type promotion[edit] One special case of implicit type conversion is type promotion, where the compiler automatically expands the binary representation of objects of integer or floating-point types. Promotions are commonly used with types smaller than the native type of the target platform's arithmetic logic unit (ALU), before arithmetic and logical operations, to make such operations possible, or more efficient if the ALU can work with more than one type. C and C++ perform such promotion for objects of boolean, character, wide character, enumeration, and short integer types which are promoted to int, and for objects of type float, which are promoted to double. Unlike some other type conversions, promotions never lose precision or modify the value stored in the object. In Java: int x = 3; double y = 3.5; System.out.println(x+y); //The output will be 6.5 Explicit type conversion[edit] Explicit type conversion is a type conversion which is explicitly defined within a program (instead of being done by a compiler for implicit type conversion). It is defined by the user in the program. double da = 3.3; double db = 3.3; double dc = 3.4; int result = (int)da + (int)db + (int)dc; //result == 9 //if implicit conversion would be used (as with "result = da + db + dc"), result would be equal to 10 There are several kinds of explicit conversion. checked Before the conversion is performed, a runtime check is done to see if the destination type can hold the source value. If not, an error condition is raised. unchecked No check is performed. If the destination type cannot hold the source value, the result is undefined. bit pattern The raw bit representation of the source is copied verbatim, and it is re-interpreted according to the destination type. This can also be achieved via aliasing. In object-oriented programming languages, objects can also be downcast : a reference of a base class is cast to one of its derived classes. C# and C++[edit] In C#, type conversion can be made in a safe or unsafe (i.e., C-like) manner, the former called checked type cast.[1] Animal animal = new Cat(); Bulldog b = (Bulldog) animal; // if (animal is Bulldog), stat.type(animal) is Bulldog, else an exception b = animal as Bulldog; // if (animal is Bulldog), b = (Bulldog) animal, else b = null animal = null; b = animal as Bulldog; // b == null In C++ the similar effect can be achieved using C++-style cast syntax. Animal* animal = new Cat; Bulldog* b = static_cast<Bulldog*>(animal); // compiles only if either Animal or Bulldog is derived from the other (or same) b = dynamic_cast<Bulldog*>(animal); // if (animal is Bulldog), b = (Bulldog*) animal, else b = nullptr animal = nullptr; b = dynamic_cast<Bulldog*>(animal); // b == nullptr Eiffel[edit] In Eiffel the notion of type conversion is integrated into the rules of the type system. The Assignment Rule says that an assignment, such as: x := y is valid if and only if the type of its source expression, y in this case, is compatible with the type of its target entity, x in this case. In this rule, compatible with means that the type of the source expression either conforms to or converts to that of the target. Conformance of types is defined by the familiar rules for polymorphism in object-oriented programming. For example, in the assignment above, the type of y conforms to the type of x if the class upon which y is based is a descendant of that upon which x is based. Definition of type conversion in Eiffel[edit] The actions of type conversion in Eiffel, specifically converts to and converts from are defined as: A type based on a class CU converts to a type T based on a class CT (and T converts from U) if either CT has a conversion procedure using U as a conversion type, or CU has a conversion query listing T as a conversion type Example[edit] Eiffel is a fully compliant language for Microsoft .NET Framework. Before development of .NET, Eiffel already had extensive class libraries. Using the .NET type libraries, particularly with commonly used types such as strings, poses a conversion problem. Existing Eiffel software uses the string classes (such as STRING_8) from the Eiffel libraries, but Eiffel software written for .NET must use the .NET string class (System.String) in many cases, for example when calling .NET methods which expect items of the .NET type to be passed as arguments. So, the conversion of these types back and forth needs to be as seamless as possible. my_string: STRING_8 -- Native Eiffel string my_system_string: SYSTEM_STRING -- Native .NET string ... my_string := my_system_string In the code above, two strings are declared, one of each different type (SYSTEM_STRING is the Eiffel compliant alias for System.String). Because System.String does not conform to STRING_8, then the assignment above is valid only if System.String converts to STRING_8. The Eiffel class STRING_8 has a conversion procedure make_from_cil for objects of type System.String. Conversion procedures are also always designated as creation procedures (similar to constructors). The following is an excerpt from the STRING_8 class: class STRING_8 ... create make_from_cil ... convert make_from_cil ({SYSTEM_STRING}) ... The presence of the conversion procedure makes the assignment: my_string := my_system_string semantically equivalent to: create my_string.make_from_cil (my_system_string) in which my_string is constructed as a new object of type STRING_8 with content equivalent to that of my_system_string. To handle an assignment with original source and target reversed: my_system_string := my_string the class STRING_8 also contains a conversion query to_cil which will produce a System.String from an instance of STRING_8. class STRING_8 ... create make_from_cil ... convert make_from_cil ({SYSTEM_STRING}) to_cil: {SYSTEM_STRING} ... The assignment: my_system_string := my_string then, becomes equivalent to: my_system_string := my_string.to_cil In Eiffel, the setup for type conversion is included in the class code, but then appears to happen as automatically as explicit type conversion in client code. The includes not just assignments but other types of attachments as well, such as argument (parameter) substitution.


Security issues[edit] In hacking, typecasting is the misuse of type conversion to temporarily change a variable's data type from how it was originally defined.[2] This provides opportunities for hackers since in type conversion after a variable is "typecast" to become a different data type, the compiler will treat that hacked variable as the new data type for that specific operation.[3]


See also[edit] Downcasting Run-time type information#dynamic cast and Java cast Type punning


References[edit] ^ Mössenböck, Hanspeter (25 March 2002). "Advanced C#: Checked Type Casts" (PDF). Institut für Systemsoftware, Johannes Kepler Universität Linz, Fachbereich Informatik. p. 5. Retrieved 4 August 2011.  at C# Tutorial ^ Jon Erickson Hacking, 2nd Edition: The Art of Exploitation 2008 1593271441 p51 "Typecasting is simply a way to temporarily change a variable's data type, despite how it was originally defined. When a variable is typecast into a different type, the compiler is basically told to treat that variable as if it were the new data type, but only for that operation. The syntax for typecasting is as follows: (typecast_data_type) variable ..." ^ Arpita Gopal Magnifying C 2009 8120338618 p.59 "From the above, it is clear that the usage of typecasting is to make a variable of one type, act like another type for one single operation. So by using this ability of typecasting it is possible for create ASCII characters by typecasting integer to its ..."


External links[edit] Casting in ABAP Casting in Ada Casting in C++ C++ Reference Guide Why I hate C++ Cast Operators, by Danny Kalev Casting in Java Implicit Conversions in C# Implicit Type Casting at Cppreference.com Static and Reinterpretation castings in C++ Upcasting and Downcasting in F# v t e Data types Uninterpreted Bit Byte Trit Tryte Word Bit array Numeric Arbitrary-precision or bignum Complex Decimal Fixed point Floating point Double precision Extended precision Half precision Long double Minifloat Octuple precision Quadruple precision Single precision Integer signedness Interval Rational Pointer Address physical virtual Reference Text Character String null-terminated Composite Algebraic data type generalized Array Associative array Class Dependent Equality Inductive List Object metaobject Option type Product Record Set Union tagged Other Boolean Bottom type Collection Enumerated type Exception Function type Opaque data type Recursive data type Semaphore Stream Top type Type class Unit type Void Related topics Abstract data type Data structure Generic Kind metaclass Parametric polymorphism Primitive data type Protocol interface Subtyping Type constructor Type conversion Type system Type theory See also platform-dependent and independent units of information Retrieved from "https://en.wikipedia.org/w/index.php?title=Type_conversion&oldid=827216419" Categories: Data typesOperators (programming)Type theoryUnary operationsHidden categories: Articles needing additional references from May 2011All articles needing additional referencesArticles with example C codeUse dmy dates from January 2012


Navigation menu Personal tools Not logged inTalkContributionsCreate accountLog in Namespaces ArticleTalk Variants Views ReadEditView history More Search Navigation Main pageContentsFeatured contentCurrent eventsRandom articleDonate to WikipediaWikipedia store Interaction HelpAbout WikipediaCommunity portalRecent changesContact page Tools What links hereRelated changesUpload fileSpecial pagesPermanent linkPage informationWikidata itemCite this page Print/export Create a bookDownload as PDFPrintable version Languages БългарскиČeštinaDanskDeutschEspañolFrançais한국어ItalianoNederlands日本語PolskiPortuguêsРусскийУкраїнськаTiếng Việt中文 Edit links This page was last edited on 23 February 2018, at 12:57. Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Terms of Use and Privacy Policy. Wikipedia® is a registered trademark of the Wikimedia Foundation, Inc., a non-profit organization. Privacy policy About Wikipedia Disclaimers Contact Wikipedia Developers Cookie statement Mobile view (window.RLQ=window.RLQ||[]).push(function(){mw.config.set({"wgPageParseReport":{"limitreport":{"cputime":"0.148","walltime":"2.813","ppvisitednodes":{"value":728,"limit":1000000},"ppgeneratednodes":{"value":0,"limit":1500000},"postexpandincludesize":{"value":25156,"limit":2097152},"templateargumentsize":{"value":249,"limit":2097152},"expansiondepth":{"value":12,"limit":40},"expensivefunctioncount":{"value":2,"limit":500},"entityaccesscount":{"value":0,"limit":400},"timingprofile":["100.00% 2772.834 1 -total"," 12.70% 352.199 12 Template:C-lang"," 1.66% 45.931 1 Template:Reflist"," 1.30% 36.109 1 Template:Refimprove"," 1.20% 33.399 1 Template:Cite_web"," 1.04% 28.874 1 Template:Ambox"," 0.78% 21.620 1 Template:About"," 0.45% 12.466 1 Template:Use_dmy_dates"," 0.44% 12.209 1 Template:Data_types"," 0.38% 10.413 1 Template:DMCA"]},"scribunto":{"limitreport-timeusage":{"value":"0.046","limit":"10.000"},"limitreport-memusage":{"value":2280094,"limit":52428800}},"cachereport":{"origin":"mw1282","timestamp":"20180223125715","ttl":1900800,"transientcontent":false}}});});(window.RLQ=window.RLQ||[]).push(function(){mw.config.set({"wgBackendResponseTime":85,"wgHostname":"mw1262"});});


Type_conversion - Photos and All Basic Informations

Type_conversion More Links

Type Conversion (aviation)Wikipedia:VerifiabilityHelp:Introduction To Referencing With Wiki Markup/1Help:Maintenance Template RemovalComputer ScienceData TypeInteger (computer Science)Floating PointString (computer Science)Type HierarchyData RepresentationPrimitive Data TypeCompound Data TypeProgramming LanguageStrong TypingWeak TypingCompilerRun Time (program Lifecycle Phase)SubroutineALGOLPascal (programming Language)Modula-2Ada (programming Language)Delphi (programming Language)ALGOL 68CompilerProgramming LanguageSubtypingRun Time (program Lifecycle Phase)C (programming Language)Unintended ConsequencesIEEE 754TruncationArithmetic Logic UnitJava (programming Language)Aliasing (computing)Object-oriented ProgrammingDowncastingC Sharp (programming Language)C++Eiffel (programming Language)Polymorphism In Object-oriented ProgrammingList Of CLI Languages.NET FrameworkHacker (computer Security)Variable (computer Science)DowncastingRun-time Type InformationType PunningTemplate:Data TypesTemplate Talk:Data TypesData TypeUnits Of InformationBitByteTernary Numeral SystemTernary Numeral SystemWord (computer Architecture)Bit ArrayArbitrary-precision ArithmeticComplex Data TypeDecimal Data TypeFixed-point ArithmeticFloating PointDouble-precision Floating-point FormatExtended PrecisionHalf-precision Floating-point FormatLong DoubleMinifloatOctuple-precision Floating-point FormatQuadruple-precision Floating-point FormatSingle-precision Floating-point FormatInteger (computer Science)SignednessInterval ArithmeticRational Data TypePointer (computer Programming)Memory AddressPhysical AddressVirtual Address SpaceReference (computer Science)Plain TextCharacter (computing)String (computer Science)Null-terminated StringComposite Data TypeAlgebraic Data TypeGeneralized Algebraic Data TypeArray Data TypeAssociative ArrayClass (computer Programming)Dependent TypeIntuitionistic Type TheoryInductive TypeList (abstract Data Type)Object (computer Science)MetaobjectOption TypeProduct TypeRecord (computer Science)Set (abstract Data Type)Union TypeTagged UnionBoolean Data TypeBottom TypeContainer (abstract Data Type)Enumerated TypeException HandlingFunction TypeOpaque Data TypeRecursive Data TypeSemaphore (programming)Stream (computing)Top TypeType ClassUnit TypeVoid TypeAbstract Data TypeData StructureGeneric ProgrammingKind (type Theory)MetaclassParametric PolymorphismPrimitive Data TypeProtocol (object-oriented Programming)Interface (computing)SubtypingType ConstructorType SystemType TheoryTemplate:Information UnitsHelp:CategoryCategory:Data TypesCategory:Operators (programming)Category:Type TheoryCategory:Unary OperationsCategory:Articles Needing Additional References From May 2011Category:All Articles Needing Additional ReferencesCategory:Articles With Example C CodeCategory:Use Dmy Dates From January 2012Discussion About Edits From This IP Address [n]A List Of Edits Made From This IP Address [y]View The Content Page [c]Discussion About The Content Page [t]Edit This Page [e]Visit The Main Page [z]Guides To Browsing WikipediaFeatured Content – The Best Of WikipediaFind Background Information On Current EventsLoad A Random Article [x]Guidance On How To Use And Edit WikipediaFind Out About WikipediaAbout The Project, What You Can Do, Where To Find ThingsA List Of Recent Changes In The Wiki [r]List Of All English Wikipedia Pages Containing Links To This Page [j]Recent Changes In Pages Linked From This Page [k]Upload Files [u]A List Of All Special Pages [q]Wikipedia:AboutWikipedia:General Disclaimer



view link view link view link view link view link