C++ General: What are different number representations?
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 1 of 1

Thread: C++ General: What are different number representations?

Hybrid View

  1. #1
    Join Date
    Oct 2002
    Location
    Timisoara, Romania
    Posts
    14,360

    C++ General: What are different number representations?

    Q: How many number representations does a computer recognize?

    A: All computers built so far are binary machines, thus the only representation known to them is binary.


    Q: Then what about decimal or hexadecimal representations?

    A: They are not known to a computer and to explain that I will go for some low-level considerations. When you type a number, for example 5, on your keyboard that numbers is stored in a registry of the keyboard controller directly as binary, as an ASCII code char, the binary representation resulting from the keyboard hardwire. Later the number is transferred to memory. At any given moment it is stored, transferred and processed in the form of 0 and 1, thus binary. Programming languages provide support for various representations such as octal, decimal and hexadecimal, by operating various transformations on the binary strings of 0 and 1. Your editor shows on screen the number you typed, 5 in our example, first by applying a transformation of the binary representation into another binary representation (to correspond for example to the ASCII code of 5, which is 53 in decimal) if the number isn’t already stored as a char code, and then by applying some graphic primitives on a memory zone where the transformed number is stored.


    Q: What can you tell me about ASCII char set?

    A: It is a set for representing characters (numbers, letters and other signs), which you can see on your keyboard, and which are treaded in the way explained above. The ASCII character code charts contain the decimal and hexadecimal values of the ASCII (American Standards Committee for Information Interchange) character set. An extended character set includes the ASCII character set and 128 other characters for graphics and line drawing, often called the "IBM character set." In this set, the decimal number 5 which in binary (on 8 bits) is 00000101 has the decimal code 53, which in binary is 00110101. To represent the numbers from direct binary representation to ASCII representation a transformation must be made, which is based on the ASCII character code charts.


    Q: What about number representation in C/C++?

    A: When you write a program in C/C++ you can choose between octal, decimal and hexadecimal representation for numbers. If we take for example decimal 55, you can also use its octal representation, 067, or its hexadecimal representation 0x37.


    Q: What conversion do I have to make between these representations when dealing with numbers?

    A: NONE. The language takes care of that.
    Code:
    int n = 55 + 0x55 + 055;
    The result is decimal 185, hexadecimal 0xB9, or octal 0271.


    Q: I still don’t understand how this is done.

    A: No need to panic; just be patient. First you have to remember there is only binary. When you write a program in any language (and let’s take C++ for example), each char you type is first put into memory and later saved on disk. Files are also stored as binary, thought most programming languages provide support for text files (ASCII files). Binary files imply no kind of transformation on data when transferred between memory and disk, while in the case of text files some conversion are made on data before transferred in one way or the other (memory to disk or disk to memory). When the compiler does its job, it starts by analyzing the source code, which is transferred from disk to memory. Based on the language’s syntax it transforms the string of chars into numbers, keywords, separators, and other terms of the language. ‘55’ is transformed as 5*10+5 = 55, ‘0x55’ as 5*16+5 = 85 and ‘055’ as 5*8+5 = 45. The results, 00110111, 01010101 and 00101101, are stored in memory and then written in the object file generated by the compiler, which is a binary file. These object file are later linked into an executable, which is also binary. When the executable is ran, its content is transferred into memory unaltered, and when the execution flow reaches that line of code, the three numbers stored in binary are added and the result, 10111001, is stored temporary in a registry and then written in memory.


    Q: Why when I try to view an executable I see squares and characters than make no sense?

    A: Most editors are text editors, thus they expect as input a text file. Its content is interpreted in terms of a character code set, such as ASCII. If you view or open for edit a binary file, its binary content is mapped on the character set, resulting characters which apparently make no sense. However, there are editors that read binary files and print the content in hexadecimal.


    Q: How do I print the result in octal, decimal and hexadecimal?

    A: You can do it in the C way or in the C++ way.
    The C way:
    Code:
    int n = 55 + 0x55 + 055;
    printf("octal: %o\n",n);	// prints "octal: 271"
    printf("decimal: %d\n",n);	// prints "decimal: 185"
    printf("hex: %x\n",n);		// prints "hex: b9"
    The C++ way
    Code:
    int n = 55+0x55+055;
    cout.flags(ios::oct);
    cout << "octal: " << n << endl;		// prints "octal: 271"
    cout.flags(ios::dec);
    cout << "decimal: " << n << endl;	// prints "decimal: 185"
    cout.flags(ios::hex);
    cout << "hex: " << n << endl;		// prints "hex: b9"

    Q: What do I have to do, if I want to convert a number to a string?

    A: You can use C/C++/MFC functions or methods.
    Direct conversions:
    • integer to string: _itoa, _i64toa, _ui64toa, _itow, _i64tow, _ui64tow
    • long integer to string: _ltoa, _ltow
    • unsigned integer to string: _ultoa, _ultow


    You can use format methods to convert to string:
    C
    Code:
    int n = 55+0x55+055;
    char str[10];	// make sure you have enough space
    sprintf(str,"%d",n);
    C++
    Code:
    int n = 55+0x55+055;
    std::stringstream sstr;
    sstr << n;
    std::string str = sstr.str();
    MFC
    Code:
    int n = 55+0x55+055;
    CString str;
    str.Format("%d",n);

    Q: What if I want to convert a string to a number?

    A: You can use direct conversion functions to convert string to:
    • double: atof, _wtof
    • integer: atoi, _atoi64, _wtoi, _wtoi64
    • long integer: atoll, _wtol, strtol, wcstol


    Also you can do this:
    C
    Code:
    int n;
    char str[] = "44";
    sscanf(str,"%d",&n);
    C++
    Code:
    int n;
    std::string str("44");
    std::stringstream sstr(str);
    sstr >> n;

    Q: And if I have a string with hexadecimal digits, like "01A4FE" how do I convert it to an array of integers {0x01, 0xA4, 0xFE}?

    A: You can use this C++ function:
    Code:
    void string_to_bytearray(std::string str, unsigned char* &array, int& size)
    {
    	int length = str.length();
    	// make sure the input string has an even digit numbers
    	if(length%2 == 1)
    	{
    		str = "0" + str;
    		length++;
    	}
    
    	// allocate memory for the output array
    	array = new unsigned char[length/2];
    	size = length/2;
    
    	std::stringstream sstr(str);
    	for(int i=0; i < size; i++)
    	{
    		char ch1, ch2;
    		sstr >> ch1 >> ch2;
    		int dig1, dig2;
    		if(isdigit(ch1)) dig1 = ch1 - '0';
    		else if(ch1>='A' && ch1<='F') dig1 = ch1 - 'A' + 10;
    		else if(ch1>='a' && ch1<='f') dig1 = ch1 - 'a' + 10;
    		if(isdigit(ch2)) dig2 = ch2 - '0';
    		else if(ch2>='A' && ch2<='F') dig2 = ch2 - 'A' + 10;
    		else if(ch2>='a' && ch2<='f') dig2 = ch2 - 'a' + 10;
    		array[i] = dig1*16 + dig2;
    	}
    }
    
    int main()
    {
    	unsigned char* array = NULL;
    	int size;
    	string_to_bytearray("01A4FE",array,size);
    
    	// ...
    	
    	delete [] array;	// make sure you release the allocated memory
    	return 0;
    }
    Or you can go all the C++ way and use a vector instead of unsigned char[]:
    Code:
    void string_to_vector(std::string str, std::vector<int> &array)
    {
    	int length = str.length();
    	// make sure the input string has an even digit numbers
    	if(length%2 == 1)
    	{
    		str = "0" + str;
    		length++;
    	}
    
    	// allocate memory for the output array
    	array.reserve(length/2);
    	
    	std::stringstream sstr(str);
    	for(int i=0; i < length/2; i++)
    	{
    		char ch1, ch2;
    		sstr >> ch1 >> ch2;
    		int dig1, dig2;
    		if(isdigit(ch1)) dig1 = ch1 - '0';
    		else if(ch1>='A' && ch1<='F') dig1 = ch1 - 'A' + 10;
    		else if(ch1>='a' && ch1<='f') dig1 = ch1 - 'a' + 10;
    		if(isdigit(ch2)) dig2 = ch2 - '0';
    		else if(ch2>='A' && ch2<='F') dig2 = ch2 - 'A' + 10;
    		else if(ch2>='a' && ch2<='f') dig2 = ch2 - 'a' + 10;
    		array.push_back(dig1*16 + dig2);
    	}
    }
    
    int main()
    {
    	std::vector<int> array;;
    	string_to_vector("bA4FE",array);
    
    	return 0;
    }

    Last edited by Andreas Masur; July 23rd, 2005 at 02:01 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center