Hello. Can someone please tell me what happens when you cast a large number to a char? For example:

char string[8];
int num = 2040;

string[0] = (char) num;

I'm working my way through a larger program to figure out what it does, but I'm not sure how to handle this situation. Normally, I'd just convert it to its corresponding ASCII character, but 2040 is obviously too large. What gets stored in string[0]? Is it just a series of characters, '2', '0', '4', '0'?

Recommended Answers

All 3 Replies

an unsigned char variable is only a value between 0 and 255 (0 and 126 signed). That means it can only contain a single numeric digit -- if you look at any ascii chart you will see that the digit '0' has a numeric value of 48, the digit '1' is 49, etc. When casting an integer to char you have to be careful that the value of the integer is between 0 and 255. Any greater value and the result of the typecase is undefined, meaning it depends on how the compiler decides to handle it.

Instead of trying to typecase the integer you should probably want to convert it to a series of ascii digits. If you have an integers value of 2048 then you will want to convert it into a series of digits '2', '0', '4' and '8'. One way to do it in C language is with sprintf()

int val = 2048;
char buf[10];
sprintf(buf,"%d", val);

The c++ way of doing it would be stringstream class. But since this is a C forum I doubt this is what you want.

#include <sstream>
int val = 2048;
std::string result;
stringstream str;
str << val;
str >> result; // convert integer to string of characters

Here's some code to demonstrate what happens when you cast an unsigned long to unsigned char...

#include <stdio.h>
#include <stdlib.h>

unsigned long myint = 1234567890;

int main(int argc, char**argv)
	int i = 0;
	unsigned char *cptr = (unsigned char*)&myint;/*cast myint to unsigned char*/

	for (i = 0; i < sizeof(unsigned long); ++i)
		fprintf(stdout, "char->%x\n", cptr[i]);/*display hex value of pointer as it walks along myint*/

	fprintf(stdout, "myint->%p\n", (void*)myint);/*dislay hex value of myint*/

Nit: that's not really demonstrating "what happens when you cast an unsigned long to unsigned char"; it's actually examining the bytes composing the unsigned long value. Close, but I'm having a bit of a pedantic moment.

#include <stdio.h>

int main(void)
   unsigned long value = 0x01234567UL;
   unsigned char byte = value;
   printf("value = %lX = %lu\n", value, value);
   printf("byte  = %X = %u\n", (unsigned)byte, (unsigned)byte);
   return 0;

/* my output
value = 1234567 = 19088743
byte  = 67 = 103

(I need to be careful about being pedantic, it greatly tends to attract criticism. :P)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.