【发布时间】:2023-03-19 01:54:01
【问题描述】:
我在 C++ 中有以下代码,它应该采用 led_pwm 十六进制变量,并将其转换为字符串 led_pwm_string。
long int led_pwm=0x0a;
std::ostringstream ostr;
ostr << std::hex << led_pwm; //use the string stream just like cout,
//except the stream prints not to stdout
//but to a string.
std::string led_pwm_string = ostr.str(); //the str() function of the stream
//returns the string
我对这段代码的唯一问题是,对于0x00 和0x0a 之间的任何led_pwm 值,它会转换为led_pwm_string 中的单个数字。这给我以后带来了麻烦。
我希望,在任何可能的情况下,led_pwm_string 始终包含一个 2 位字符串。因此,如果led_pwm 是0x01(例如),那么led_pwm_string 将是01,而不仅仅是1。
【问题讨论】:
标签: c++ formatting converters