• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 592
  • Last Modified:

Outputting a char as an unsigned int

Hi,

I'm attempting to output every possible char as an unsigned int (see code snippet). But this gives the following:

0
...
126
127
4294967168
4294967169
...
4294967295


But what I'm wanting is:
0
...
126
127
128
129
...
255


Thanks,
Uni
char mut=0;
cout<<(unsigned int)mut<<endl;
for(unsigned int i=0;i<256;i++){
	mut++
	cout<<(unsigned int)mut<<endl;
}

Open in new window

0
Unimatrix_001
Asked:
Unimatrix_001
  • 2
1 Solution
 
UrosVidojevicCommented:
You must use unsigned char.
char type can contain negative values, which causes problems in your case, when you are converting char to unsigned int.

unsigned char mut=0;
for(unsigned int i=0;i<256;i++){
        cout<<(unsigned int)mut<<endl;
            mut++;
}

Also, I shortened your example little bite, because it contained some  unnecessary parts.
0
 
Unimatrix_001Author Commented:
Thank you... :)
0
 
Infinity08Commented:
You could also do it as short as this :

        char c = 0;
        do {
          std::cout << (unsigned int) ((unsigned char) c) << std::endl;
        } while (++c);

or even :

        char c = 0;
        do {
          printf("%d\n", (unsigned char) c);
        } while (++c);
0
 
Infinity08Commented:
or %u instead of %d ;)
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now