Linux内核中如何将char[]字符串转换为int?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6139493/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 04:17:06  来源:igfitidea点击:

How convert a char[] string to int in the Linux kernel?

clinuxlinux-kernelkernel

提问by caeycae

How convert char[] to int in linux kernel

如何在linux内核中将char[]转换为int

with validation that the text entered is actually an int?

验证输入的文本实际上是一个整数?

int procfile_write(struct file *file, const char *buffer, unsigned long count,
       void *data)
{

   char procfs_buffer[PROCFS_MAX_SIZE];

    /* get buffer size */
   unsigned long procfs_buffer_size = count;
   if (procfs_buffer_size > PROCFS_MAX_SIZE ) {
       procfs_buffer_size = PROCFS_MAX_SIZE;
   }

   /* write data to the buffer */
   if ( copy_from_user(procfs_buffer, buffer, procfs_buffer_size) ) {
       return -EFAULT;
   }

   int = buffer2int(procfs_buffer, procfs_buffer_size);

   return procfs_buffer_size;
}

采纳答案by FrankH.

See the various incarnations of kstrtol()in #include <include/linux/kernel.h>in your friendly linux source tree.

在友好的 linux 源代码树中查看kstrtol()in的各种化身#include <include/linux/kernel.h>

Which one you need depends on whether the *bufferis a user or a kernel address, and on how strict your needs on error handling / checking of the buffer contents are (things like, is 123qxinvalid or should it return 123?).

您需要哪一个取决于*buffer是用户地址还是内核地址,以及您对错误处理/检查缓冲区内容的需求有多严格(例如,123qx无效还是应该返回123?)。

回答by Blazes

Use atoi and isdigit (note isdigit just takes a char). http://www.cplusplus.com/reference/clibrary/cctype/isdigit/

使用 atoi 和 isdigit (注意 isdigit 只需要一个字符)。 http://www.cplusplus.com/reference/clibrary/cctype/isdigit/

回答by Vikram.exe

Because of the unavailability of a lot of common function/macros in linux kernel, you can not use any direct function to get integer value from a string buffer.

由于 linux 内核中许多常用函数/宏不可用,因此您不能使用任何直接函数从字符串缓冲区中获取整数值。

This is the code that I have been using for a long time for doing this and it can be used on all *NIX flavors (probably without any modification).

这是我长期以来一直使用的代码,它可以用于所有 *NIX 风格(可能无需任何修改)。

This is the modified form of code, which I used a long time back from an open source project (don't remember the name now).

这是修改后的代码形式,我从一个开源项目中使用了很长时间(现在不记得名字了)。

#define ISSPACE(c)  ((c) == ' ' || ((c) >= '\t' && (c) <= '\r'))
#define ISASCII(c)  (((c) & ~0x7f) == 0)
#define ISUPPER(c)  ((c) >= 'A' && (c) <= 'Z')
#define ISLOWER(c)  ((c) >= 'a' && (c) <= 'z')
#define ISALPHA(c)  (ISUPPER(c) || ISLOWER(c))
#define ISDIGIT(c)  ((c) >= '0' && (c) <= '9')

unsigned long mystr_toul (
    char*   nstr,
    char**  endptr,
    int base)
{
#if !(defined(__KERNEL__))
    return strtoul (nstr, endptr, base);    /* user mode */

#else
    char* s = nstr;
    unsigned long acc;
    unsigned char c;
    unsigned long cutoff;
    int neg = 0, any, cutlim;

    do
    {
        c = *s++;
    } while (ISSPACE(c));

    if (c == '-')
    {
        neg = 1;
        c = *s++;
    }
    else if (c == '+')
        c = *s++;

    if ((base == 0 || base == 16) &&
        c == '0' && (*s == 'x' || *s == 'X'))
    {
        c = s[1];
        s += 2;
        base = 16;
    }
    if (base == 0)
        base = c == '0' ? 8 : 10;

    cutoff = (unsigned long)ULONG_MAX / (unsigned long)base;
    cutlim = (unsigned long)ULONG_MAX % (unsigned long)base;
    for (acc = 0, any = 0; ; c = *s++)
    {
        if (!ISASCII(c))
            break;
        if (ISDIGIT(c))
            c -= '0';
        else if (ISALPHA(c))
            c -= ISUPPER(c) ? 'A' - 10 : 'a' - 10;
        else
            break;

        if (c >= base)
            break;
        if (any < 0 || acc > cutoff || (acc == cutoff && c > cutlim))
            any = -1;
        else
        {
            any = 1;
            acc *= base;
            acc += c;
        }
    }

    if (any < 0)
    {
        acc = INT_MAX;
    }
    else if (neg)
        acc = -acc;
    if (endptr != 0)
        *((const char **)endptr) = any ? s - 1 : nstr;
    return (acc);
#endif
}

回答by Sonny

I use sscanf() (the kernel version) to scan from a string stream, and it works on 2.6.39-gentoo-r3. Frankly, I could never get simple_strtol() to work in the kernel--I am currently figuring out why this doesn't work on my box.

我使用 sscanf()(内核版本)从字符串流中扫描,它适用于 2.6.39-gentoo-r3。坦率地说,我永远无法让 simple_strtol() 在内核中工作——我目前正在弄清楚为什么这在我的盒子上不起作用。

  ...
  memcpy(bufActual, calc_buffer, calc_buffer_size);
  /* a = simple_strtol(bufActual, NULL, 10); */ // Could not get this to work
  sscanf(bufActual, "%c%ld", &opr, &a); // places '+' in opr and a=20 for bufActual = "20+##代码##"
  ...