- How do I convert a Char to Int?
- 4 Answers 4
- How to convert a single char into an int [duplicate]
- 11 Answers 11
- You can make use of atoi() function
- How to convert int to char/string and vice versa in linux(gcc)?
- 5 Answers 5
- Not the answer you’re looking for? Browse other questions tagged c sockets gcc printf or ask your own question.
- Related
- Hot Network Questions
- Subscribe to RSS
- 32bit C program no longer converting char to int on 64 bit OS Linux
- 2 Answers 2
- Convert char to int in C and C++
- 12 Answers 12
How do I convert a Char to Int?
So I have a String of integers that looks like «82389235» , but I wanted to iterate through it to add each number individually to a MutableList . However, when I go about it the way I think it would be handled:
This adds numbers completely unrelated to the string to the list. Yet, if I use println to output it to the console it iterates through the string perfectly fine.
How do I properly convert a Char to an Int ?
4 Answers 4
That’s because num is a Char , i.e. the resulting values are the ascii value of that char.
This will do the trick:
The map could be further simplified:
The variable num is of type Char . Calling toInt() on this returns its ASCII code, and that’s what you’re appending to the list.
If you want to append the numerical value, you can just subtract the ASCII code of 0 from each digit:
Which is a bit nicer like this:
This works with a map operation too, so that you don’t have to create a MutableList at all:
Alternatively, you could convert each character individually to a String , since String.toInt() actually parses the number — this seems a bit wasteful in terms of the objects created though:
For clarity, the zeroAscii answer can be simplified to
as Char — Char -> Int. If you are looking to minimize the number of characters typed, that is the shortest answer I know. The
may be the clearest answer, though, as it does not require the reader to know anything about the low-level details of ASCII codes. The toString().toInt() option requires the least knowledge of ASCII or Kotlin but is a bit weird and may be most puzzling to the readers of your code (though it was the thing I used to solve a bug before investigating if there really wasn’t a better way!)
Источник
How to convert a single char into an int [duplicate]
I have a string of digits, e.g. «123456789», and I need to extract each one of them to use them in a calculation. I can of course access each char by index, but how do I convert it into an int?
I’ve looked into atoi(), but it takes a string as argument. Hence I must convert each char into a string and then call atoi on it. Is there a better way?
11 Answers 11
You can utilize the fact that the character encodings for digits are all in order from 48 (for ‘0’) to 57 (for ‘9’). This holds true for ASCII, UTF-x and practically all other encodings (see comments below for more on this).
Therefore the integer value for any digit is the digit minus ‘0’ (or 48).
is synonymous to
However I find the first c — ‘0’ far more readable.
Or you could use the «correct» method, similar to your original atoi approach, but with std::stringstream instead. That should work with chars as input as well as strings. (boost::lexical_cast is another option for a more convenient syntax)
(atoi is an old C function, and it’s generally recommended to use the more flexible and typesafe C++ equivalents where possible. std::stringstream covers conversion to and from strings)
You can make use of atoi() function
The answers provided are great as long as you only want to handle Arabic numerals, and are working in an encoding where those numerals are sequential, and in the same place as ASCII.
This is almost always the case.
If it isn’t then you need a proper library to help you.
Let’s start with ICU.
- First convert the byte-string to a unicode string. (Left as an exercise for the reader).
- Then use uchar.h to look at each character.
- if we the character is UBool u_isdigit (UChar32 c)
- then the value is int32_t u_charDigitValue ( UChar32 c )
Or maybe ICU has some function to do it for you — I haven’t looked at it in detail.
Источник
How to convert int to char/string and vice versa in linux(gcc)?
I want to know the method of converting an integer into char/string and vice-versa also.
I have already used sprintf(&charvar,»%d»,&intvar) but it produces wrong output, possibly garbage.
i have also heard atoi() in gcc has bugs.Reference:GCC atoi bug
What is the other method to convert string/char back to int ?
Actually i want to send an integer from one machine to another using SOCK_STREAM .
//EDIT : I forgot to tell that sprintf() does conversion and returns positive value.
5 Answers 5
If you want to send an integer to another machine you can send it as binary data, just by sending the intvar directly to the stream, you don’t have to convert it to a char first. That will only introduce problems with knowing the length of the data as different values generate different lengths of strings.
Please read the manual of ‘sprintf’ and ‘sscanf’, and maybe their safer versions are proper for you.
Remove the ampersand before intvar :
- Here, I assume that &charvar is of correct type, which it probably isn’t.
- Even though it might not make much difference here, it’s a good to get into the habit of using snprintf in preference to sprintf .
Here’s some example code:
You cannot sprintf to a variable. You need a buffer for it, because of possible several digits and the trailing zero. Moreover, the argument should be the int variable, not its address.
(buffer will be filled with ‘4’, ‘2’ and trailing ‘\0’).
your sprintf is wrong.You should write sprintf(string,»%d»,integer); If you want to send an integer over the network and thats why you want to convert it into string have a look at htons
with these functions you can convert an integer to network format and avoid different endianness problems! If you just want to convert it to bytes you can do something like this:
If you want your string to have the value of the int then you should use sprintf.
Not the answer you’re looking for? Browse other questions tagged c sockets gcc printf or ask your own question.
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.10.8.40416
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Источник
32bit C program no longer converting char to int on 64 bit OS Linux
a simple question:
this function worked perfectly on my 32 Bit Linux then I got a 64 Bit Linux and now it is no longer working. I’ve narrowed it down to this function in converting the data from Char to Int. it no longer does this. this is where I am stuck at right now. all this functions is doing is taking a format like this 100×100 then chopping out the x and keeping the two numbers on both sides then changing them into Int’s.
Using atoi is now returning junk now that I am running it on this 64bit Linux. what function call do I have to use that will make it work again only on both 32 and 64 bit Linux programs now?
2 Answers 2
These lines which you use to assign memory to copy the passed string are nonsense.
Would be better as
It’s a wonder that your earlier version worked at all!
EDIT
Lets walk through it:
The malloc allocates memory for a char* pointer — previously 4 bytes, now 8.
The (int)malloc converts the address of the memory allocated to an integer.
The char x = then stores the integer in 8 bits. This has nothing to do with the length of the string you will copy.
Next char str1[x]; assigns an array of a size totally unrelated to the length of string you will copy. Even if you did have the right length, it need to be one element longer to take the nul terminator. If it worked before, is pure luck that you ended up with a long enough array.
But switching to a different compiler has shown up this bug.
So rather than say I haven’t answered your question, please correct your mistake and see if it fixes the problem. Maybe it will, maybe not: I haven’t looked past line 3 to see if there are any other howlers.
Источник
Convert char to int in C and C++
How do I convert a char to an int in C and C++?
12 Answers 12
Depends on what you want to do:
to read the value as an ascii code, you can write
to convert the character ‘0’ -> 0 , ‘1’ -> 1 , etc, you can write
Explanation:
a — ‘0’ is equivalent to ((int)a) — ((int)’0′) , which means the ascii values of the characters are subtracted from each other. Since 0 comes directly before 1 in the ascii table (and so on until 9 ), the difference between the two gives the number that the character a represents.
Well, in ASCII code, the numbers (digits) start from 48. All you need to do is:
Or, since the character ‘0’ has the ASCII code of 48, you can just write:
C and C++ always promote types to at least int . Furthermore character literals are of type int in C and char in C++.
You can convert a char type simply by assigning to an int .
char is just a 1 byte integer. There is nothing magic with the char type! Just as you can assign a short to an int, or an int to a long, you can assign a char to an int.
Yes, the name of the primitive data type happens to be «char», which insinuates that it should only contain characters. But in reality, «char» is just a poor name choice to confuse everyone who tries to learn the language. A better name for it is int8_t, and you can use that name instead, if your compiler follows the latest C standard.
Though of course you should use the char type when doing string handling, because the index of the classic ASCII table fits in 1 byte. You could however do string handling with regular ints as well, although there is no practical reason in the real world why you would ever want to do that. For example, the following code will work perfectly:
You have to realize that characters and strings are just numbers, like everything else in the computer. When you write ‘a’ in the source code, it is pre-processed into the number 97, which is an integer constant.
So if you write an expression like
this is actually equivalent to
which is then going through the C language integer promotions
and then truncated to a char to fit the result type
There’s a lot of subtle things like this going on between the lines, where char is implicitly treated as an int.
Источник