|
Field/Data Types and Data TypingHere are notes comparing the intricacies of how various programming environments use and convert among different data types.
| Topics this page:
|
|
MS .NET Framework BittableWhen data is transferred between Microsoft's dot Net Framework and unmanaged (DCOM) code (through P/Invoke), data types which do have the same in-memory representations -- known as non-blittable types -- require conversion (marshaling) as they are passed back and forth. These are Boolean, Char, String, Object, and arrays of these types. C# Number Formatting
The presentation of numbers (for the current culture) can be automatically formatted by specifying these codes within curly braces, listed in alphabetical order: public void WriteAsBytes(int value){ bytes[] = BitConverter.GetBytes(value); foreach(byte b in bytes){ Console.Write("0x{0:X2}", b); string message = String.Format("0x{0:X2}", b); Debug.Write(message); } Debug.WriteLine(""); } If the above code is called by WriteAsBytes(32), then this would display 0x20 0x00 0x00 0x00. Parsing strings is the opposite process from formatting. Implicit conversions & CastingThis table ablove lists data types from smallest to largest such that implicit conversions can flow from top to bottom, but not upstream.
To explicitly cast to a smaller datatype in Java:
myInteger = (int) myLongInteger java automatically casts to a larger datatype, but will throw a fit rather than going smaller. To expliciitly cast to a smaller datatype in C#:
long longValue = Int64.MaxValue; int intValue = (int) longValue; Note the .MaxValue property avialable only to C# programmers. Also, with C#, unsigned can go signed, but not the other way.
"Boxing" transforms a value type to a reference type by creating a temporary reference type "box" on the heap. To convert a String to a double: doubleOffset = Double.valueOf( offset ).doubleValue(); To convert a String to a floating point in Ruby (since the language is object oriented): "1".to_i + 1 |
Object Identifier Naming Conventions
Instance identifiers (names) cannot be a Word Reserved for Java. Prefix to field names for indicating how the datum is stored: include file adovbs.inc provides constants for values identifying data type: adInteger 3 adSingle 4 adDouble 5 adCurrency 6 adDate 7 adBoolean 11 adVariant 12 adBinary 128 adChar 129 adNumeric 131 adDBDate 133 adDBTime 134 adDBTimeStamp 135
|
|
Data Types
|
Numeric Sign DefaultThis C program (from Christopher Sawtell) tests whether the char inherent data type is signed or unsigned.This is dependent on the design of the processor used by your compiler. Early PDP-11 and VAX-11 computers had automatic sign extention of char. This means that the range of char is from -128 through to +127. The trend is toward unsigned char as the default.
| char a; unsigned char b; a = b = 128; a >>= 1; b >>= 1; printf ( "\nChar is %ssigned by default.\n\n", a == b ? "un" : "" ); } |
SQL Data Types
Oracle-SQL has no data type boolean. The Oracle character set can be displayed by using these SQL statements:
SQL> select * from nls_database_parameters where parameter like '%CHARACTERSET%'; |
BLOBs and Other SQL3 Datatypes
Type conversion between SQL and Java in Castor Unlike C or C++, Java primitive (inherent) datatypes are portable because they each occupy exactly the same amount of memory on all Java-supporting machines.
|
Type Conversion Functions
Java does not have a method to convert boolean data types (False == 0) to numeric data type. Roedy Green presents Java type conversion code as a HTML table or a Java 1.4 applet with source code that considers implied encoding translation when interconverting byte [] and String. "8859_1" encoding simply chops the high byte off or pads the high byte with 0s. When arithmetic is performed using two variables of different types, the value of the variables with the norrower type is promoted to wider type. This is called arithmetic-promotion conversion.
|
Literals
Because, by default, a numeric literal is either a double or an int, double and float literals are declared a special way. So remember to append the symbol shown in the "Default Value" column above. To avoid confusion, use the upper-case code (L) even though the lower case (l) is valid.
|
Constants
Math.PI in Java and M_PI in C's Math library.
~=2.718281828459045... — Leonhard Euler's number e, the base of natural logarithms,
such that ln(e^1) = 1 defined by
The names of constants are by convention UPPER CASE. However, in Java boolean true and false are in lower case. The C programming language defines these constants as double datatypes in its ISO C99 Standard: 7.12 Mathematics C /usr/include/Math.h library:
Other constants:
Java does not automatically declare φ (Greek letter Phi pronounced "fee") ~=1.61803... — (1+the square root of 5)/2 — the basis for the Golden Rectangles and Spirals found in nature (sunflowers, nautilus shells, and the formation of galaxies). Phi is the limit of the ratios of the numbers in the Fibonnacci sequence, where each number is the sum of the two before it (q = 1 + 1/q) for
Dividing each number by the number before it (eg., 55/34) yields Phi (through convergence by oscillation). To define constant PHI in Java:
private static final int PHI = 1.61803;
To define constant PHI in Oracle SQL:
PHI := 1.618034;
from the formula (1/p + 1/p2 or p3 - p - 1), called the Padovan sequence series after architect Richard Padovan of Padua (100 miles from Pisa where Fibonacci lived) [Nexus Network Journal, vol 4, no. 3 (Summer 2002)] The ratio between adjacent numbers yield a constant ratio of 1.324718. This was nicknamed the "Plastic Number" in 1928 by its discoverer Dom Hans Van Der Laan because it generates amazing, interconnected commensurate design patterns, many of which suggest 3D applications.
|
Hex
For example, decimal 63 is written as '63' in decimal, '077' in octal, or 0x3F, 0X3F, 0x3f, or 0X3f in hexadecimal format. All integer constants are treated as 32-bit integers. Negative numbers are obtained by prefacing the integer constant with the unary negation operator (-). Java Literal References defined in the java.lang package are used to test Bit Patterns of returned values defined in IEEE 754:
These literals are considered non-ordinal. Tthe comparison x == Float.NaN returns false even if x contains Float.NaN. So test for them using static methods Float.isNaN(float) or Double.isNaN(double) from the java.lang package.
To determine the properties, use the java.lang.Character class in the SDK:
char ch;
// if (Character.isLetter(ch)); // if (Character.getType('a') == Character.LOWERCASE_LETTER); With JavaScript, isNaN(numvalue) returns true if numvalue from parseFloat and parseInt is Not a Number.
|
String Objects
char string_2[] = "Hello"; // compiler calculates char string_3[6] = "Hello"; // 5+null character The C language reads a string until it encounters a null character (\0). So a trick C programmers use to quickly truncate a string is to inserting a null character in that string causes all remaining characters in that string to be ignored.
strcat(dest, src); is therefore risky.
assert(src != NULL); strncat(dest, src, sizeof(dest)-strlen(dest)-1); dest[sizeof(dest)-1] = '\0';
strcpy(dest, src); is risky.
assert(src != NULL); strncpy(dest, src, sizeof(dest)); Unlike later versions of the javac compiler, awareness of assert is disabled by default in version 1.4. So you will have to activate it as part of the compilation command:
JavaJava string literals are represented internally by an instance of a String object, withthe tostring() method automatically created for every class.
String s1 = "something";
But the Java compiler actually interprets:
Java does not actually create another object if both s1 and s2 have the same value. So initialize strings with different values or use StringBuffer.
The use of "==" between two strings will always return false because that
operator evaluates the addresses rather than the value of two objects.
if( s1.equals(s2) )
if( s1.equalsIgnoreCase(s2) ) if( s1.compareTo(s2) < 0 ) Best of all, make localized comparisons using the default locale:
To compare the same key several times, or to compare strings which are likely to be different even from the first characters, convert objects for bitwise comparison using CollationKey
Collator myCollator = Collator.getInstance();
CollationKey[] keys = new CollationKey[3]; keys[0] = myCollator.getCollationKey("Tom"); sort( keys ); ... if( keys[i].compareTo( keys[j] ) > 0 ) Insteading of hard-coding strings in programs, use a resource file method that looks up the value of the string. This allows you to dynamically change the text without recompiling. For best performance, such as within tight running loops threads, 1) declare the size of strings, 2) use StringBuffer, and 3) append to strings rather than concatenating them with the + plus operator. Examples:
StringBuffer sb = new StringBuffer(50);
sb.append("Hello");
sb.append("there");
Unlike a String, StringBuffers are mutable (can be modified).
Currency Data Type
Java does not have a Currency data type. Java displays currency using a function that is sensitive to formatting requirements specific to the user's locale.
DatesJava dates are not a primitive within java.lang._____.TYPE, but from class java.util.Date. Programming Date, Time, and Calendar Functions
|
Wrapper ClassesEach primitive class in Java has an associated Wrapper class, which simply contains the primitive value. The primitive name is usually the lowercase version of the wrapper, except for char and int.
Character is the wrapper class for the char primitive. A Wrapper class object is created by calling the Wrapper class constructor with the appropriate primitive value as a parameter to the constructor. For every Wrapper class except character, you can also construct a Wrapper class object by passing in a string representation of the value into the constructor. For example: int MyInt = 409; Integer intObject = new Integer(MyInt); Integer intObject2 = new Integer("409"); If the string you pass to the constructor is not formatted correctly for the Wrapper class type, the constructor will throw a NumberFormatException exception error. equals method provided by the base Object class. For example, based on the previous example, the following would be true:
To get a primitive value back out of a wrapper, use a method provided by each Wrapper class object:
Byte -> public byte byteValue();
Any of the numeric Wrapper classes can also be retrieved into any numeric type. The Wrapper classes include a valueOf() method which accepts a string parameter representing a value, then constructs and returns a Wrapper class instance of the same class.
|
Related Topics:
| Your first name: Your family name: Your location (city, country): Your Email address: |
Top of Page
Thank you! |