Problem with unsigned int

Thread Starter

thomassabu

Joined Jun 24, 2013
8
Dear All,

i wrote the following a code for pic16f88. But not getting the correct output.

I am getting the correct output till b=0 to 32768. but if i give the value greater than 32768, am obtaining an undesired output with a negative symbol. Someone please help me. Thanks in advance.

#include<htc.h>
#include<stdio.h>
#include "lcd.h"

#define _XTAL_FREQ 4e6
void main()
{
ANSELH=0x00;
TRISB=0x01;
PORTB=0x00;

lcd_init();
lcd_clear();
unsigned int b=65535;
char a[10]="0";

while(1)
{
sprintf(a,"%d",b);
lcd_goto(0);
lcd_puts(a);
}
 
Last edited:

WBahn

Joined Mar 31, 2012
30,086
Be sure to take it as an opportunity to gain valuable insight into how the printf() family of functions work.

When you passed the variable b to the printf() function, all it got was a pattern of 16 bits. The format string tells the function how to interpret that pattern. The information in the format string is.

The bit takaway, for now, is that whenever you aren't getting results that make sense and there is a printf() family function involved, carefully examine the format string to make sure that what you are really telling the function to do actually does match what you wanted to tell it to do. It's a common mistake and one that you will make from time to time as long as you continue to write code.
 

ErnieM

Joined Apr 24, 2011
8,377
The last take-away from this process may be the most important: the sprintf() functions are HUGE... I had a memory increase of some 4K in a project when first including them.

These functions do so many things you drag in code you do not need,like code to print signed ints when all you need are unsigned ints, which are much simpler and need far less code. There is often a function such as itoa() (Integer TO Ascii) which is small and dedicated to one task.

The moral is in limited memory embedded code it is far better to use small atomic functions then large one size fits all functions.
 

WBahn

Joined Mar 31, 2012
30,086
The last take-away from this process may be the most important: the sprintf() functions are HUGE...
Totally unrelated to the OP's problem, but a very, very worthwhile point to make anytime we see anyone using one of these functions for an embedded or otherwise resource-starved implementation.
 
Top