Question
printf with 2's compliment
Posted on July 13, 2013 at 08:46
I ported the printf functions to UART3. I am reading some gyro data from a digital chip that gives it's results in 2's compliment. So I get the raw data and print the integer that I stored it in. But the printf function is not converting to a decimal number, so I never get negative numbers.
So I have to convert it manually with the code below. the printf statement I use is printf(''%f'',data); why does it not see that the integer is negative and just print an unsigned value?For example: 0xFFFF = -1 in 2's compliment. But the printf will print 65535.<code>float get_gyro(char axis) //Get the gyro data at that axis in degrees/sec{ unsigned int high; //I have changed these to a signed int and had the same results unsigned int low; int data = 0; float dps = 0; float offset = 0x00; switch(axis) { case 'x': low = gyro_read(OUT_X_L); high = gyro_read(OUT_X_H); data = (low | (high<<8)); //Put high and low bytes into one 16 bit number offset = gyro_x_offset; break; case 'y': low = gyro_read(OUT_Y_L); high = gyro_read(OUT_Y_H); data = (low | (high<<8)); offset = gyro_y_offset; break; case 'z': low = gyro_read(OUT_Z_L); high = gyro_read(OUT_Z_H); data = (low | (high<<8)); offset = gyro_z_offset; break; default: break; } /**** For some reason printf does not do convertion of 2's complement. This data will always be a 16 bit number from the gyro ****/ if(data&0x8000)//If its a negative number { data = ((data ^ 0xFFFF) +1)*-1; //Convert From 2's Comp to Decimal } if(data < 0) { data = data + offset; }else{ data = data - offset; } dps = data*gyro_sens; return (dps);}</code> #printf #2's-compliment