简体   繁体   English

在C中将int转换为char的问题

[英]Issues with converting int to char in C

I've wrote a small function for debug purpose which sends string via USB to a terminal : 我编写了一个用于调试目的的小函数,该函数通过USB将字符串发送到终端:

void localprint(char* msg){
if(strlen(msg) > 60){
            usb_sendData(msg,60);
}
else usb_sendData(msg,strlen(msg));

} the function works fine for strings like : }该函数适用于像这样的字符串:

localprint(" I'm a test" ), 

the message is displayed on terminal. 该消息显示在终端上。 Now I want to get the adcValue which is an int on the terminal, for I've tried : 现在我想获取adcValue ,它是终端上的int ,因为我已经尝试过:

char t= (char)(((int)'0')+getADCValue(9)); // getting the ADC value of 0th channel 
localprint(&t);

this doens't work at all , I'Ve also tried : 这根本不起作用,我也尝试过:

char t= (char) getADCVAlue(9);
localprint(&t);

it doesn't work neither. 它也不起作用。 So my question is any idea how can I do that . 所以我的问题是我该怎么做。 I'm using uC STM32f10xx and ARM gcc. 我正在使用uC STM32f10xx和ARM gcc。 thanks for any hint 谢谢你的提示

Without knowing anything about the range of possible ints, something like this will work: 在不了解可能的整数范围的情况下,类似这样的方法将起作用:

char buffer[32];
sprintf(buffer, "%d", getADCVAlue(9));
localprint(buffer);

Since you did 0+ , I'm assuming it's one digit, so you could go 由于您输入0+ ,我假设它是一位数字,所以您可以

char buffer[2];
buffer[0] = '0' + getADCVAlue(9);
buffer[1] = '\0';
localprint(buffer);

Answer from John3136 will work fine if you replace sprintf with some lightweight implementation of this, eg xsprintf from elm-chan which I found extremely helpful in embedded programming. 如果将sprintf替换为某些轻量级实现,则John3136的回答会很好用,例如elm-chan的 xsprintf ,我发现它对嵌入式编程非常有帮助。 Or you must have some stubs for system calls like _sbrk if you want to use sprintf . 或者,如果要使用sprintf则必须具有一些用于_sbrk类的系统调用的存根。

I can't comment solution from John3136 because I don't have enough reputation. 我没有评论John3136的解决方案,因为我没有足够的声誉。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM