0

Hello, I need some advice on how this function outputs the left zeros so everything will be even at 16 bits

string conv (int num, int base) {
	if (num == 0) 
		return "0000000000000000";
	
	char NUMS[] = "0123456789ABCDEF";
	string result = "";
	
	do {
		result.push_back (NUMS[num % base]);
		num /= base;
	} while (num != 0);
     
	return string (result.rbegin(), result.rend());
}

Current Output:
100111110101

GOAL:
0000100111110101

Thanks in advance!

2
Contributors
1
Reply
2
Views
5 Years
Discussion Span
Last Post by histrungalot
0

Try string streams:

#include <iostream>
#include <iomanip>
#include <sstream>
using namespace std;
string conv (int num, int base,int pad=0) {
   if (num == 0) 
      return "0000000000000000";
   char NUMS[] = "0123456789ABCDEF";
   string result = "";
   do {
      result.push_back (NUMS[num % base]);
      num /= base;
   } while (num != 0);
   stringstream strStrm;
   if (pad) 
      strStrm << setfill('0') << setw(pad);
   strStrm << string (result.rbegin(), result.rend());
   return strStrm.str();
}
int main(){
   cout << conv(2549,2) << endl;
   cout << conv(2549,2,16) << endl;
   return 0;
}

Output:

$ ./a.out
100111110101
0000100111110101

Do more testing.

Edited by histrungalot: Added pad

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.