How to Convert a Number to String and Vice Versa in C++

Converting integer to string in C

In

char y = x + '0';

put the character code (ASCII or whatever character code your system implements) of '0' and add 5 to it then again convert that integer to an ASCII(/UTF-8 or any other character encoding) character that's what your output(5) will be.

Behind the scenes this is what's happening:

y = 5 + 48  ;for ASCII/UTF-8 character code of '0' is 48
y = 53

and ASCII/UTF-8 char for 53 is '5'.

It does not convert a string to an integer. It just gives you the equivalent character.
We can convert an int(0-127) to a char or vice-versa, output will be an ASCII/UTF-8 value. char are stored as short int in memory. i.e. they are 8-bit int values.

How compiler is converting integer to string and vice versa

To convert a string to an integer, take each character in turn and if it's in the range '0' through '9', convert it to its decimal equivalent. Usually that's simply subtracting the character value of '0'. Now multiply any previous results by 10 and add the new value. Repeat until there are no digits left. If there was a leading '-' minus sign, invert the result.

To convert an integer to a string, start by inverting the number if it is negative. Divide the integer by 10 and save the remainder. Convert the remainder to a character by adding the character value of '0'. Push this to the beginning of the string; now repeat with the value that you obtained from the division. Repeat until the divided value is zero. Put out a leading '-' minus sign if the number started out negative.

Here are concrete implementations in Python, which in my opinion is the language closest to pseudo-code.

def string_to_int(s):
i = 0
sign = 1
if s[0] == '-':
sign = -1
s = s[1:]
for c in s:
if not ('0' <= c <= '9'):
raise ValueError
i = 10 * i + ord(c) - ord('0')
return sign * i

def int_to_string(i):
s = ''
sign = ''
if i < 0:
sign = '-'
i = -i
while True:
remainder = i % 10
i = i / 10
s = chr(ord('0') + remainder) + s
if i == 0:
break
return sign + s

Convert Listint to string and vice versa?

"Use the force, Linq!" - Obi Enum Kenobi

using System.Linq;

List<Int32> numbers = new List<Int32>()
{
1,
2,
3,
4
};

String asString = String
.Join(
", ",
numbers.Select( n => n.ToString( CultureInfo.InvariantCulture ) )
);

List<Int32> fromString = asString
.Split( "," )
.Select( c => Int32.Parse( c, CultureInfo.InvariantCulture ) );

When converting to and from strings that are read by machines, not humans, it's important to avoid using ToString and Parse without using CultureInfo.InvariantCulture to ensure consistent formatting regardless of a user's culture and formatting settings.

FWIW, I have my own helper library that adds this useful extension method:

public static String ToStringInvariant<T>( this T value )
where T : IConvertible
{
return value.ToString( c, CultureInfo.InvariantCulture );
}

public static String StringJoin( this IEnumerable<String> source, String separator )
{
return String.Join( separator, source );
}

Which tidies things up somewhat:

String asString = numbers
.Select( n => n.ToStringInvariant() )
.StringJoin( ", " );

List<Int32> fromString = asString
.Split( "," )
.Select( c => Int32.Parse( c, CultureInfo.InvariantCulture ) );

convert string to number and vice versa in C (NOT C++)

Both of these are C functions:

  • atoi is in stdlib.h
  • sprintf is in stdio.h

And since these are included as part of C, neither require C++ streams.

How to convert char to int, and vice versa?

Are you talking about a single digit character, like '1' or '9'? Then you would do something like this:

char c = '5';      
int x = c - '0'; // x == 5

Digit encodings are consecutive in all character character coding schemes (ASCII, EBCDIC, etc.), so subtracting the code for '0' gives you the right value.

Are you talking about converting the character encoding to an integer? Then all you need to do is assign the character value to an int:

int x = '5'; // x contains the character encoding of '5' - in ASCII, 53

Are you talking about converting a character string, like "12" or "42"? Then you would need to use one of the sscanf, strtol, or atoi library functions (or roll your own equivalent). Given

char str[] = "123";
int x;

you would do

sscanf( str, "%d", &x ); 

or

x = atoi( str ); 

or

char *chk;
x = (int) strtol( str, &chk, 10 );
if ( !isspace( *chk ) && *chk != 0 )
// str contained a non-numeric character, handle as appropriate

how to convert a symbol into a string and vice versa in CLIPS

CLIPS> (str-cat red)
"red"
CLIPS> (sym-cat "red")
red
CLIPS> (str-cat 17)
"17"
CLIPS> (string-to-field "17")
17
CLIPS> (integer 17.3)
17
CLIPS> (float 17)
17.0
CLIPS> (round 17.3)
17
CLIPS> (explode$ "a b c")
(a b c)
CLIPS> (implode$ (create$ a b c))
"a b c"
CLIPS>

Convert integer to character and vice versa

Why dont you use an other type like uint16_t that can be used for UCS2 ? I mean char is used for ascii and extended 0-255 ~ uint8_t, if you need more dont use char.

uint16_t c=302;

Converting an int to a pseudo-random string and vice versa

In the comments I was wrong about the stream cipher. You actually need a block cipher, but the size of your block must be 24 bits (for 16 million integers). See this question and the answer: https://crypto.stackexchange.com/q/18988

These types of ciphers are called Format-preserving encryption (FPE). One such FPE is called FF1.

There is a C# implementation of FF1 on github: https://github.com/a-tze/FPE.Net



Related Topics



Leave a reply



Submit