Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert from IBM floating point to IEEE floating point standard and Vice Versa- In C#?

Was looking for a way to IEEE floating point numbers to IBM floating point format for a old system we are using.

Is there a general formula we can use in C# to this end.

like image 588
aiw Avatar asked Dec 28 '10 23:12

aiw


1 Answers

// http://en.wikipedia.org/wiki/IBM_Floating_Point_Architecture
// float2ibm(-118.625F) == 0xC276A000
// 1 100 0010    0111 0110 1010 0000 0000 0000
// IBM/370 single precision, 4 bytes
// xxxx.xxxx xxxx.xxxx xxxx.xxxx xxxx.xxxx
// s|-exp--| |--------fraction-----------|
//    (7)          (24)
// value = (-1)**s * 16**(e - 64) * .f   range = 5E-79 ... 7E+75
static int float2ibm(float from)
{
    byte[] bytes = BitConverter.GetBytes(from);
    int fconv = (bytes[3] << 24) | (bytes[2] << 16) | (bytes[1] << 8)| bytes[0];

    if (fconv == 0) return 0;
    int fmant = (0x007fffff & fconv) | 0x00800000;
    int t = (int)((0x7f800000 & fconv) >> 23) - 126;
    while (0 != (t & 0x3)) { ++t; fmant >>= 1; }
    fconv = (int)(0x80000000 & fconv) | (((t >> 2) + 64) << 24) | fmant;
    return fconv; // big endian order
}

I changed a piece of code called static void float_to_ibm(int from[], int to[], int n, int endian) the code above can be run correctly in PC from is little endian float number. return value is big endian ibm float number but stored in type int.

like image 183
speeding Avatar answered Oct 10 '22 08:10

speeding