Conversion between int and char [] in C ++

Source: Internet
Author: User
Tags 04x print format

 

1 Integer Conversion string sprintf

 

In the header file # include <stdio. h>

Syntax: int sprintf (string format, mixed [ARGs]...);

Return Value: String Length (strlen)

Conversion character

 

=-

% Indicates the percentage, which is not converted.

The % C integer is converted to the corresponding ASCII character.

% D integer to decimal place.

% F times the precision number to a floating point number.

% O integer to octal.

% S integer to string.

% X integer to lowercase hexadecimal.

% X integer to uppercase hexadecimal.

=-

<?

$ Money = 123.1

$ Formatted = sprintf ("% 06.2f", $ money); // The variable $ formatted value is "123.10"

$ Formatted = sprintf ("% 08.2f", $ money); // The variable $ formatted value is "00123.10"

$ Formatted = sprintf ("%-08.2f", $ money); // The variable $ formatted value is "123.1000"

$ Formatted = sprintf ("%. 2f %", 0.95*100); // format as a percentage

?>

%% 08.2f explanation:

% Start character

0 indicates the "fill in character". If the length is insufficient, fill it with 0.

8. Total length after formatting

2f decimal point length, that is, 2 digits

The value of rows 3rd of limit is "00123.10". Explanation:

Because 2f is (2 bits) + decimal point (1) + first 123 (3 bits) = 6 bits, the total length is 8 bits, so it is represented by a [fill-in character] 0, that is, 00123.10

The value of rows 4th of limit is "123.1000". Explanation:

-It indicates a reverse operation. Then, the blank character 0 is added to the end.

Format a numeric string

 

One of the most common applications of sprintf is to print Integers to strings. Therefore, spritnf can be replaced in most cases.

ITOA.

For example:

// Print the integer 123 into a string and save it in S.

Sprintf (S, "% d", 123); // generate "123"

You can specify the width. If the width is insufficient, spaces are filled on the left:

Sprintf (S, "% 8d % 8d", 123,456 7); // generate: "123 4567"

Of course, you can also align left:

Sprintf (S, "%-8d % 8d", 123,456 7); // generate: "123 4567"

You can also print the data in hexadecimal format:

Sprintf (S, "% 8x", 4567); // lowercase hexadecimal notation, with 8 width positions and right alignment

Sprintf (S, "%-8x", 4568); // in hexadecimal notation, the width occupies 8 positions and is left aligned.

In this way, the hexadecimal string of an integer is easy to obtain, but when printing the hexadecimal content, we usually want an equal-width format with 0 on the left, what should we do?

Simply add 0 to the number that represents the width.

Sprintf (S, "% 08x", 4567); // generate: "201711d7"

You can also use this left-side 0 Complement Method to print the 10-in-hexadecimal format with "% d" above.

Pay attention to a symbol extension problem: for example, if we want to print a short INTEGER (short)-1 memory hexadecimal representation, on the Win32 platform,

A short type occupies 2 bytes, So we naturally want to print it with 4 hexadecimal numbers:

Short Si =-1;

Sprintf (S, "% 04x", Si );

Why is "ffffffff" generated? Because spritnf is a Variable Parameter Function, except the first two parameters, the following parameters are not of type security,

There is no way for a function to know whether a 4-byte integer or a 2-byte short integer is pressed in the parameter stack before the function call through a "% x ".,

Therefore, a 4-byte processing method is adopted, which leads to the symbol extension during parameter pressure stack, which is a 32-bit integer-1. When printing, the four locations are insufficient,

Print out the 8-bit 16 hexadecimal values of 32-bit integer-1.

If you want to see the original form of Si, you should let the compiler do 0 extension instead of symbol extension (during expansion, the left side of the binary complement 0 instead of the sign bit ):

Sprintf (S, "% 04x", (unsigned short) Si );

You can. Or:

Unsigned short Si =-1;

Sprintf (S, "% 04x", Si );

Sprintf and printf can also print integer strings in octal, using "% O ". Note that both hexadecimal and hexadecimal are not supported.

Negative numbers are all unsigned. In fact, they are directly hexadecimal or octal representation of the internal code of the variable.

Control floating point print format

The printing and format control of floating point numbers is another common function of sprintf. Floating Point Numbers are controlled by the format character "% F", which is guaranteed by default.

Keep the six digits after the decimal point, for example:

Sprintf (S, "% F", 3.1415926); // generate "3.141593"

But sometimes we want to control the print width and decimal places, then we should use the format "% m. NF", where the M Table

The print width. N indicates the number of digits after the decimal point. For example:

Sprintf (S, "% 10.3f", 3.1415626); // generate: "3.142"

Sprintf (S, "%-10.3f", 3.1415626); // generate: "3.142"

Sprintf (S, "%. 3f", 3.1415626); // The total width is not specified, resulting in: "3.142"

Pay attention to one question, you guess

Int I = 100;

Sprintf (S, "%. 2f", I );

What will it do? 100.00 "? Right? Try it on your own and try the following:

Sprintf (S, "%. 2f", (double) I );

The first one is definitely not the correct result, because, as mentioned above, the caller does not know that the format controller corresponding to I is "% F" when the parameter is pressed ".

When the function is executed, the function itself does not know that the four bytes that were pushed into the stack were integers. Therefore, the four bytes that saved the integer I were forcibly forced

The floating point format is interpreted as a mess. However, if someone is interested in manually coding a floating point number,

You can use this method to check whether the result of your manual arrangement is correct.

 

 

 

 

2 string to integer: atoi and atol. This is the standard library of C.


C language library function name: atoi

Function: converts a string to an integer.

Name Source: Abbreviation of array to integer.

Prototype: int atoi (const char * nptr );

Function Description: nptr string. If the first non-space character does not exist or is neither a number nor a plus or minus sign, zero is returned. Otherwise, type conversion is started,

If a non-number or Terminator/0 is detected, the conversion is stopped and the integer number is returned.

Header file: # include <stdlib. h>

Program example:

1)

# Include <stdlib. h>

# Include <stdio. h>

Int main (void)

{

Int N;

Char * STR = "12345.67 ";

N = atoi (STR );

Printf ("string = % s integer = % d/N", STR, N );

Return 0;

}

Execution result

String = 12345.67 integer = 12345

2)

# Include <stdlib. h>

# Include <stdio. h>

Int main ()

{

Char A [] = "-100 ";

Char B [] = "123 ";

Int C;

C = atoi (A) + atoi (B );

Printf ("c = % d/N", C );

Return 0;

}

Execution result

C = 23

Simple implementation of atoi function source code:

Int my_atoi (const char * Str ){

Int result = 0;

Int signal = 1;/* The default value is positive */

If (* STR> = '0' & * STR <= '9') | * STR = '-' | * STR = '+ '){

If (* STR = '-' | * STR = '+ '){

If (* STR = '-')

Signal =-1;/* negative input */

STR ++;

}

}

Else return 0;

/* Start conversion */

While (* STR> = '0' & * STR <= '9 ')

Result = Result * 10 + (* STR ++-'0 ');

Return Signal * result;

}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.