Lol! i should have looked at this thread during the day!
I have made an algorithm based on your original post and does seem to be quite similar
public class IntFloat {
static public void main(String[] arg)
{
Random random=new Random(-1);
int j=5;
for (int i=0;i<50;i++)
{
float val=(float) (random.nextDouble()*(maxNum[j]*2)-maxNum[j])/10000;
for (int k=1;k<9;k++)
{
System.out.println("digits: "+k+ " bits needed: "+maskBitCount[k]+" rounding: false input: "+val +" -> "+decode(encode(val,k,false),k));
System.out.println("digits: "+k+ " bits needed: "+maskBitCount[k]+" rounding: true input: "+val +" -> "+decode(encode(val,k,true),k));
}
}
}
static final private int[] multiplier = {1,10,100,1000,10000,100000,1000000,10000000,100000000};
static final private int[] maxNum = {1,9,99,999,9999,99999,999999,9999999,99999999,999999999};
static final private int[] maskBitCount = {0,6,10,13,17,21,24,28,31};
static final private int[] mask={0,63,1023,8191,131071,2097151,16777215,268435455,2147483647};
static public int encode(float val,int digitsCount,boolean round)
{
int max=maxNum[digitsCount];
int count=digitsCount;
// test for outliers
if (val>max) return max*2;
if (val<-max) val=-max;
// get the integer component of the input value
int temp=Math.abs((int) val);
// count the decimal places
while (temp>0)
{
temp/=10;
count--;
}
if (count<0)
count=0;
if (round ) return (Math.round(val*multiplier[count])+max)+(max*2+1)*count;
return ((int) (val*multiplier[count])+max)+(max*2+1)*count;
}
static public float decode(int val,int digitsCount)
{
// get the maximum number able to be represented by the number of digits
final int max=maxNum[digitsCount];
// calculate the total possible number of numbers able to represented
final int temp=(max*2+1);
// extract the number of decimal places
int count = val/temp;
// extract the digits
int digits = val%temp;
return ((float)(digits-max))/multiplier[count];
}