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;
}