2014-11-17 3 views
0

"led_pwm"16 진수 변수를 "led_pwm_string"문자열로 변환해야하는 C++에서 다음 코드를 사용합니다.C++에서 int를 2 자리 숫자로 변환

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 

I이 코드가 유일한 문제는, 0x00에서 0x0a led_pwm 사이의 임의의 값에 대해, 그것이 "led_pwm_string"단일 숫자로 변환한다는 것이다. 나중에 나에게 문제가된다.

모든 가능한 상황에서 "led_pwm_string"에는 항상 2 자리 문자열이 포함되어 있습니다. 그래서 "led_pwm"이 0x01 (예를 들면)이면 "led_pwm_string"은 "01"이 될 것이고 "1"이 될 것입니다.

나는 충분히 맑았 으면 좋겠다.

답변

5

봅니다 :

ostr << std::hex << std::setw(2) << std::setfill('0') << led_pwm; 

당신은 #include <iomanip>해야 할 수도 있습니다.

+1

분명히 효과가있었습니다. 감사! –

+0

질문에 "대답 함"으로 표시하십시오. – bialpio

관련 문제