Jump to content

rand() and negative numbers

Recommended Posts

I am attempting to use the rand and srand functions to generate a "random" pause between sections of my code. I am using the 18F2510, have added the rand.pic18.lib file to my project and have included the rand.h file in the program.

I keep getting negative numbers in my random number variable. I don't understand this as the routine states that an unsigned short should be returned from the call. I wrote the following as a test of the rand and srand functions to see what is happening.

char buff[9];
char* ptr;
unsigned short random_int;

for(i = 0; i < 10; i++)
	random_int = rand();
	ptr = itoa(random_int,buff,10);	//	contained in stdlib.h

The values I get form this are as follows:

15322, -16984, -9592, -22399, -30702, -32477, 4657, 8984, 12677, 6234

Can someone please explain to me what I am doing wrong?

I just modified the code to give me hex numbers instead of decimals (radix 16 instead of 10). The results are 3bda, bda8, da88, a881, 8812, 8123, 1231, 2318, 3185, 185a. None of these are negative from the standpoint of an unsigned short. Why am I getting signed numbers in this?

What is the lprintf (or itoa) doing that it should not? What have I missed? Can someone please explain this to me?

Edited by mityeltu
Link to comment
Share on other sites

Ok, Well, I manged to figure out how to fix this anyway.

The 'light' function uitoa_dec() will give me an unsigned number that I can use in the display. It still makes no sense to me why a defined unsigned short placed in a function requiring an unsigned short would somehow produce a signed result.

Anyway, problem solved.

Link to comment
Share on other sites

Try changing 

random_int = rand();


random_int = rand() >> 1;

This will reduce the possible random range by half but your code will operate on the positive half of the int range (when itoa implicitly converts unsigned to signed it will deal with lover half of the unsigned range which converted to signed will contain only positives).

Link to comment
Share on other sites

Join the conversation

You are posting as a guest. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Create New...