kstrtouint和kstrtou8函数定义在文件kernel/lib/kstrtox.c中,原形如下:

	233 /**
	234  * kstrtoint - convert a string to an int
	235  * @s: The start of the string. The string must be null-terminated, and may also
	236  *  include a single newline before its terminating null. The first character
	237  *  may also be a plus sign or a minus sign.
	238  * @base: The number base to use. The maximum supported base is 16. If base is
	239  *  given as 0, then the base of the string is automatically detected with the
	240  *  conventional semantics - If it begins with 0x the number will be parsed as a
	241  *  hexadecimal (case insensitive), if it otherwise begins with 0, it will be
	242  *  parsed as an octal number. Otherwise it will be parsed as a decimal.
	243  * @res: Where to write the result of the conversion on success.
	244  *
	245  * Returns 0 on success, -ERANGE on overflow and -EINVAL on parsing error.
	246  * Used as a replacement for the obsolete simple_strtoull. Return code must
	247  * be checked.
	248  */
	249 int kstrtoint(const char *s, unsigned int base, int *res)
	250 {
	251         long long tmp;
	252         int rv;
	253
	254         rv = kstrtoll(s, base, &tmp);
	255         if (rv < 0)
	256                 return rv;
	257         if (tmp != (long long)(int)tmp)
	258                 return -ERANGE;
	259         *res = tmp;
	260         return 0;
	261 }
	262 EXPORT_SYMBOL(kstrtoint);


	294 int kstrtou8(const char *s, unsigned int base, u8 *res)
	295 {
	296         unsigned long long tmp;
	297         int rv;
	298
	299         rv = kstrtoull(s, base, &tmp);
	300         if (rv < 0)
	301                 return rv;
	302         if (tmp != (unsigned long long)(u8)tmp)
	303                 return -ERANGE;
	304         *res = tmp;
	305         return 0;
	306 }

s是输入字符串,base可以是10(10进制)或16(16进制),或者是0自动识别:
base 为10,则字符串转换成10进制数,使用kstrtoint函数;
base 为16,则字符串转换成16进制数,使用kstrtou8函数;

res为存放转换后的数值;

当没有错误时返回值是0。

具体使用demo:

static ssize_t gpio_led_store(struct device *dev, struct device_attribute *attr,
						const char *buf, size_t size)
{
	int val;
	int ret;

	ret = kstrtoint(buf, 10, &val); //输入一个字符然后转换成10进制整形数

        if (ret) {
		printk("%s: kstrtoint error return %d\n", __func__, ret);
		return -1;
        }

	if (val== 1) { //如果echo 1 到节点则调用

		printk("-czd-: _%s_ :gpio pull up\n", __func__);
		gpio_direction_output(gpio_led, val); //设置GPIO电平为高电平

	} else if (val == 0) { //如果echo 0 到节点则调用

		printk("-czd-: _%s_ :gpio pull down\n", __func__);
		gpio_direction_output(gpio_led, val); //设置GPIO电平为低电平

	} else {

		printk("I only support 0 or 1 to ctrl led\n");

	}
	return size;
}

Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐