Linux의 itoa 기능은 어디에 있나요?
itoa()숫자를 문자열로 변환하는 데 매우 편리한 기능입니다.에 Linux가 되어 있지 않은 것 같습니다.itoa(), 반드시 를 해야 합니까?sprintf(str, "%d", num)
편집: 죄송합니다. 이 기계는 비표준이며, 다양한 비표준 전원 케이블을 연결했습니다.libc
~로itoa()는 실제로했듯이 사용하시는 .여러 유용한 코멘트에 의해 언급되었듯이, 를 사용하는 것이 가장 좋습니다.sprintf(target_string,"%d",source_int)더 좋다.snprintf(target_string, size_of_target_string_in_bytes, "%d", source_int)★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ 간결하거나 쿨하지 않다는 것을 알고 있습니다itoa(), Once, Everywhere (tm) , Run Everywhere ) ;- ) 、 , 、 , , , ,
여기 오래된 답변이 있습니다.
것은 .gcc libc에는 「」는 포함되지 .itoa()다른 여러 플랫폼과 마찬가지로 기술적으로 표준의 일부가 아니기 때문입니다.자세한 내용은 여기를 참조하십시오.주의:
#include <stdlib.h>
물론 당신은 이미 알고 있습니다. 왜냐하면 당신은 그것을 사용하고 싶었기 때문입니다. itoa()아마 다른 플랫폼에서 사용한 후 Linux에서 사용했을 것입니다만...코드(위 링크에서 참조)는 다음과 같습니다.
예
/* itoa example */
#include <stdio.h>
#include <stdlib.h>
int main ()
{
int i;
char buffer [33];
printf ("Enter a number: ");
scanf ("%d",&i);
itoa (i,buffer,10);
printf ("decimal: %s\n",buffer);
itoa (i,buffer,16);
printf ("hexadecimal: %s\n",buffer);
itoa (i,buffer,2);
printf ("binary: %s\n",buffer);
return 0;
}
출력:
Enter a number: 1750 decimal: 1750 hexadecimal: 6d6 binary: 11011010110
이게 도움이 됐으면 좋겠네요!
itoa 는 표준 C 함수가 아닙니다.직접 구현할 수 있습니다.Kernighan and Ritchie's 초판에 실렸지C 프로그래밍 언어(60페이지)The C Programming Language ('K&R2') 제2판에는 다음과 같은 기능이 실장되어 있습니다.itoa(64페이지)를 참조해 주세요.이 책에서는 이 구현에 관한 몇 가지 문제에 대해 언급하고 있습니다.예를 들어 가장 부정적인 수치를 올바르게 처리하지 못하고 있다는 사실도 있습니다.
/* itoa: convert n to characters in s */
void itoa(int n, char s[])
{
int i, sign;
if ((sign = n) < 0) /* record sign */
n = -n; /* make n positive */
i = 0;
do { /* generate digits in reverse order */
s[i++] = n % 10 + '0'; /* get next digit */
} while ((n /= 10) > 0); /* delete it */
if (sign < 0)
s[i++] = '-';
s[i] = '\0';
reverse(s);
}
★★reverse위에서 사용한 것은, 2 페이지 전에 실장되어 있습니다.
#include <string.h>
/* reverse: reverse string s in place */
void reverse(char s[])
{
int i, j;
char c;
for (i = 0, j = strlen(s)-1; i<j; i++, j--) {
c = s[i];
s[i] = s[j];
s[j] = c;
}
}
그것을 직업으로 하는 사람들의 코드를 읽는 것은 당신에게 큰 도움이 될 것이다.
MySQL에서 어떻게 했는지 보세요.이 소스는 매우 잘 설명되어 있으며, 도처에서 발견된 해킹된 솔루션보다 훨씬 더 많은 것을 가르쳐 줄 것입니다.
여기에서는, 전술한 실장을 소개하고 있습니다.링크는 참조용으로, 실장 전체를 참조하기 위해서 사용할 필요가 있습니다.
char *
int2str(long int val, char *dst, int radix,
int upcase)
{
char buffer[65];
char *p;
long int new_val;
char *dig_vec= upcase ? _dig_vec_upper : _dig_vec_lower;
ulong uval= (ulong) val;
if (radix < 0)
{
if (radix < -36 || radix > -2)
return NullS;
if (val < 0)
{
*dst++ = '-';
/* Avoid integer overflow in (-val) for LLONG_MIN (BUG#31799). */
uval = (ulong)0 - uval;
}
radix = -radix;
}
else if (radix > 36 || radix < 2)
return NullS;
/*
The slightly contorted code which follows is due to the fact that
few machines directly support unsigned long / and %. Certainly
the VAX C compiler generates a subroutine call. In the interests
of efficiency (hollow laugh) I let this happen for the first digit
only; after that "val" will be in range so that signed integer
division will do. Sorry 'bout that. CHECK THE CODE PRODUCED BY
YOUR C COMPILER. The first % and / should be unsigned, the second
% and / signed, but C compilers tend to be extraordinarily
sensitive to minor details of style. This works on a VAX, that's
all I claim for it.
*/
p = &buffer[sizeof(buffer)-1];
*p = '\0';
new_val= uval / (ulong) radix;
*--p = dig_vec[(uchar) (uval- (ulong) new_val*(ulong) radix)];
val = new_val;
while (val != 0)
{
ldiv_t res;
res=ldiv(val,radix);
*--p = dig_vec[res.rem];
val= res.quot;
}
while ((*dst++ = *p++) != 0) ;
return dst-1;
}
편집: 아래 제 기능과 동일한 기능을 방금 알게 되었습니다.이 기능은 C++11에서 도입되어 적어도 c++0x 확장을 이노블로 하면 적어도 4.5의 최신 버전의 gcc에서 사용할 수 있습니다.
Not only is
itoa missing from gcc, it's not the handiest function to use since you need to feed it a buffer. I needed something that could be used in an expression so I came up with this:
std::string itos(int n)
{
const int max_size = std::numeric_limits<int>::digits10 + 1 /*sign*/ + 1 /*0-terminator*/;
char buffer[max_size] = {0};
sprintf(buffer, "%d", n);
return std::string(buffer);
}
보통 사용하는 것이 안전합니다.snprintf대신sprintf버퍼는 오버런에 대해 면역이 될 수 있는 크기로 되어 있습니다.
http://ideone.com/mKmZVE 의 예를 참조해 주세요.
Linux의 itoa 기능은 어디에 있나요?
Linux에는 이러한 기능이 없습니다.대신 이 코드를 사용합니다.
/*
=============
itoa
Convert integer to string
PARAMS:
- value A 64-bit number to convert
- str Destination buffer; should be 66 characters long for radix2, 24 - radix8, 22 - radix10, 18 - radix16.
- radix Radix must be in range -36 .. 36. Negative values used for signed numbers.
=============
*/
char* itoa (unsigned long long value, char str[], int radix)
{
char buf [66];
char* dest = buf + sizeof(buf);
boolean sign = false;
if (value == 0) {
memcpy (str, "0", 2);
return str;
}
if (radix < 0) {
radix = -radix;
if ( (long long) value < 0) {
value = -value;
sign = true;
}
}
*--dest = '\0';
switch (radix)
{
case 16:
while (value) {
* --dest = '0' + (value & 0xF);
if (*dest > '9') *dest += 'A' - '9' - 1;
value >>= 4;
}
break;
case 10:
while (value) {
*--dest = '0' + (value % 10);
value /= 10;
}
break;
case 8:
while (value) {
*--dest = '0' + (value & 7);
value >>= 3;
}
break;
case 2:
while (value) {
*--dest = '0' + (value & 1);
value >>= 1;
}
break;
default: // The slow version, but universal
while (value) {
*--dest = '0' + (value % radix);
if (*dest > '9') *dest += 'A' - '9' - 1;
value /= radix;
}
break;
}
if (sign) *--dest = '-';
memcpy (str, dest, buf +sizeof(buf) - dest);
return str;
}
나는 이토아의 실장을 시도했다.그것은 바이너리, 8진수, 10진수, 16진수로 동작하는 것 같다.
#define INT_LEN (10)
#define HEX_LEN (8)
#define BIN_LEN (32)
#define OCT_LEN (11)
static char * my_itoa ( int value, char * str, int base )
{
int i,n =2,tmp;
char buf[BIN_LEN+1];
switch(base)
{
case 16:
for(i = 0;i<HEX_LEN;++i)
{
if(value/base>0)
{
n++;
}
}
snprintf(str, n, "%x" ,value);
break;
case 10:
for(i = 0;i<INT_LEN;++i)
{
if(value/base>0)
{
n++;
}
}
snprintf(str, n, "%d" ,value);
break;
case 8:
for(i = 0;i<OCT_LEN;++i)
{
if(value/base>0)
{
n++;
}
}
snprintf(str, n, "%o" ,value);
break;
case 2:
for(i = 0,tmp = value;i<BIN_LEN;++i)
{
if(tmp/base>0)
{
n++;
}
tmp/=base;
}
for(i = 1 ,tmp = value; i<n;++i)
{
if(tmp%2 != 0)
{
buf[n-i-1] ='1';
}
else
{
buf[n-i-1] ='0';
}
tmp/=base;
}
buf[n-1] = '\0';
strcpy(str,buf);
break;
default:
return NULL;
}
return str;
}
저는 https://github.com/wsq003/itoa_for_linux을 선호합니다.
지금까지 가장 빠른 itoa()가 될 것입니다.성능상의 이유로 sprintf() 대신 itoa()를 사용하기 때문에 기능이 제한된 빠른 itoa()가 적절하고 가치가 있습니다.
glibc 내부 구현
glibc 2.28에는 다음과 같은 내부 구현이 있습니다.
내부적으로는 여러 곳에서 사용되고 있습니다만, 어떻게 노출될 수 있는지 알 수 없었습니다.
적어도 그것을 추출할 의향이 있다면 그것은 견고한 구현이어야 한다.
이 질문에서는 자신의 롤 방법을 묻습니다.C에서 int를 문자열로 변환하려면 어떻게 해야 합니까?
다음 함수는 주어진 숫자의 문자열 표현을 유지하는 데 충분한 메모리만 할당하고 표준 값을 사용하여 문자열 표현을 이 영역에 씁니다.sprintf방법.
char *itoa(long n)
{
int len = n==0 ? 1 : floor(log10l(labs(n)))+1;
if (n<0) len++; // room for negative sign '-'
char *buf = calloc(sizeof(char), len+1); // +1 for null
snprintf(buf, len+1, "%ld", n);
return buf;
}
잊지 말고free필요한 경우 할당된 메모리 업:
char *num_str = itoa(123456789L);
// ...
free(num_str);
N.B. snprintf가 n-1바이트를 복사하므로 snprintf(buf, len+1, "%ld", n)를 호출해야 합니다(snprintf(buf, len, "%ld", n) 뿐만 아니라).
Linux의 itoa 기능은 어디에 있나요?
~하듯이itoa()는 C에서는 표준이 아닙니다.다양한 기능 시그니처를 가진 다양한 버전이 존재합니다.
char *itoa(int value, char *str, int base);*nix에서는 공통입니다.
Linux에서 찾을 수 없거나 코드가 이식성을 제한하지 않을 경우 코드가 이를 자체 소유로 만들 수 있습니다.
다음은 에 문제가 없는 버전입니다.INT_MIN및 문제 버퍼를 처리합니다.NULL또는 버퍼가 부족하면 반환됩니다.NULL.
#include <stdlib.h>
#include <limits.h>
#include <string.h>
// Buffer sized for a decimal string of a `signed int`, 28/93 > log10(2)
#define SIGNED_PRINT_SIZE(object) ((sizeof(object) * CHAR_BIT - 1)* 28 / 93 + 3)
char *itoa_x(int number, char *dest, size_t dest_size) {
if (dest == NULL) {
return NULL;
}
char buf[SIGNED_PRINT_SIZE(number)];
char *p = &buf[sizeof buf - 1];
// Work with negative absolute value
int neg_num = number < 0 ? number : -number;
// Form string
*p = '\0';
do {
*--p = (char) ('0' - neg_num % 10);
neg_num /= 10;
} while (neg_num);
if (number < 0) {
*--p = '-';
}
// Copy string
size_t src_size = (size_t) (&buf[sizeof buf] - p);
if (src_size > dest_size) {
// Not enough room
return NULL;
}
return memcpy(dest, p, src_size);
}
아래는 임의의 베이스를 처리하는 C99 이후 버전입니다.[ 2 ]36]
char *itoa_x(int number, char *dest, size_t dest_size, int base) {
if (dest == NULL || base < 2 || base > 36) {
return NULL;
}
char buf[sizeof number * CHAR_BIT + 2]; // worst case: itoa(INT_MIN,,,2)
char *p = &buf[sizeof buf - 1];
// Work with negative absolute value to avoid UB of `abs(INT_MIN)`
int neg_num = number < 0 ? number : -number;
// Form string
*p = '\0';
do {
*--p = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"[-(neg_num % base)];
neg_num /= base;
} while (neg_num);
if (number < 0) {
*--p = '-';
}
// Copy string
size_t src_size = (size_t) (&buf[sizeof buf] - p);
if (src_size > dest_size) {
// Not enough room
return NULL;
}
return memcpy(dest, p, src_size);
}
C89 이후의 준거 코드의 경우, 내부 루프를
div_t qr;
do {
qr = div(neg_num, base);
*--p = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"[-qr.rem];
neg_num = qr.quot;
} while (neg_num);
로서 맷 J를 썼다, 거기에 있습니다.itoa겠지만, 표준입니다.이 코드를 사용하면 휴대성이 향상됩니다.snprintf.
직접 복사를 버퍼링 할:64비트 정수itoa 육각:.
char* itoah(long num, char* s, int len)
{
long n, m = 16;
int i = 16+2;
int shift = 'a'- ('9'+1);
if(!s || len < 1)
return 0;
n = num < 0 ? -1 : 1;
n = n * num;
len = len > i ? i : len;
i = len < i ? len : i;
s[i-1] = 0;
i--;
if(!num)
{
if(len < 2)
return &s[i];
s[i-1]='0';
return &s[i-1];
}
while(i && n)
{
s[i-1] = n % m + '0';
if (s[i-1] > '9')
s[i-1] += shift ;
n = n/m;
i--;
}
if(num < 0)
{
if(i)
{
s[i-1] = '-';
i--;
}
}
return &s[i];
}
참고: 길고 싶어 오랫동안 32비트 기계를 바꾼다.긴 경우에 32비트 정수를. int에 m은 radix.언제 radix이 감소(변수 i)캐릭터들의 수를 증가시킨다고 합니다언제 radix 증가하고,(더 나은)캐릭터들의 수를 줄이다.부호 없는 데이터 형식의 경우, 내가 16일 1+.
인쇄하고 싶은 경우:
void binary(unsigned int n)
{
for(int shift=sizeof(int)*8-1;shift>=0;shift--)
{
if (n >> shift & 1)
printf("1");
else
printf("0");
}
printf("\n");
}
snprintf로의 대체가 완료되지 않았습니다!
이것은 2, 8, 10, 16의 베이스만을 대상으로 하는 반면, 이토아는 2에서 36 사이의 베이스에 대해 효과가 있습니다.
32번 기지를 대체할 사람을 찾고 있었으니, 내 코드를 써야 할 것 같아!
다음은 Archana 솔루션의 훨씬 개선된 버전입니다.1-16 기수 및 숫자 <= 0에 대해 작동하며 메모리가 부족하면 안 됩니다.
static char _numberSystem[] = "0123456789ABCDEF";
static char _twosComp[] = "FEDCBA9876543210";
static void safestrrev(char *buffer, const int bufferSize, const int strlen)
{
int len = strlen;
if (len > bufferSize)
{
len = bufferSize;
}
for (int index = 0; index < (len / 2); index++)
{
char ch = buffer[index];
buffer[index] = buffer[len - index - 1];
buffer[len - index - 1] = ch;
}
}
static int negateBuffer(char *buffer, const int bufferSize, const int strlen, const int radix)
{
int len = strlen;
if (len > bufferSize)
{
len = bufferSize;
}
if (radix == 10)
{
if (len < (bufferSize - 1))
{
buffer[len++] = '-';
buffer[len] = '\0';
}
}
else
{
int twosCompIndex = 0;
for (int index = 0; index < len; index++)
{
if ((buffer[index] >= '0') && (buffer[index] <= '9'))
{
twosCompIndex = buffer[index] - '0';
}
else if ((buffer[index] >= 'A') && (buffer[index] <= 'F'))
{
twosCompIndex = buffer[index] - 'A' + 10;
}
else if ((buffer[index] >= 'a') && (buffer[index] <= 'f'))
{
twosCompIndex = buffer[index] - 'a' + 10;
}
twosCompIndex += (16 - radix);
buffer[index] = _twosComp[twosCompIndex];
}
if (len < (bufferSize - 1))
{
buffer[len++] = _numberSystem[radix - 1];
buffer[len] = 0;
}
}
return len;
}
static int twosNegation(const int x, const int radix)
{
int n = x;
if (x < 0)
{
if (radix == 10)
{
n = -x;
}
else
{
n = ~x;
}
}
return n;
}
static char *safeitoa(const int x, char *buffer, const int bufferSize, const int radix)
{
int strlen = 0;
int n = twosNegation(x, radix);
int nuberSystemIndex = 0;
if (radix <= 16)
{
do
{
if (strlen < (bufferSize - 1))
{
nuberSystemIndex = (n % radix);
buffer[strlen++] = _numberSystem[nuberSystemIndex];
buffer[strlen] = '\0';
n = n / radix;
}
else
{
break;
}
} while (n != 0);
if (x < 0)
{
strlen = negateBuffer(buffer, bufferSize, strlen, radix);
}
safestrrev(buffer, bufferSize, strlen);
return buffer;
}
return NULL;
}
당신은 sprintf 대신 이 프로그램을 사용할 수 있습니다.
void itochar(int x, char *buffer, int radix);
int main()
{
char buffer[10];
itochar(725, buffer, 10);
printf ("\n %s \n", buffer);
return 0;
}
void itochar(int x, char *buffer, int radix)
{
int i = 0 , n,s;
n = s;
while (n > 0)
{
s = n%radix;
n = n/radix;
buffer[i++] = '0' + s;
}
buffer[i] = '\0';
strrev(buffer);
}
만약 당신이 그것을 많이 부르고 있다면, "그냥 snprintf를 사용하라"는 조언은 짜증날 수 있다.원하는 것은 다음과 같습니다.
const char *my_itoa_buf(char *buf, size_t len, int num)
{
static char loc_buf[sizeof(int) * CHAR_BITS]; /* not thread safe */
if (!buf)
{
buf = loc_buf;
len = sizeof(loc_buf);
}
if (snprintf(buf, len, "%d", num) == -1)
return ""; /* or whatever */
return buf;
}
const char *my_itoa(int num)
{ return my_itoa_buf(NULL, 0, num); }
RedHat6와 GCC 컴파일러에서 _itoa(...)를 사용한 적이 있습니다.그건 효과가 있다.
언급URL : https://stackoverflow.com/questions/190229/where-is-the-itoa-function-in-linux
'itsource' 카테고리의 다른 글
| EOF 시뮬레이션 방법 (0) | 2022.07.17 |
|---|---|
| Vuex를 통한 양방향 데이터 바인딩 (0) | 2022.07.17 |
| VueJ: v-model과 :value를 동시에 사용 (0) | 2022.07.17 |
| 포인터를 이해하기 위한 장벽은 무엇이며, 이를 극복하기 위해 무엇을 할 수 있을까요? (0) | 2022.07.17 |
| Android에서 ScrollView를 프로그래밍 방식으로 스크롤할 수 있습니까? (0) | 2022.07.17 |