Example #1
0
func TestFloat32_Random(t *testing.T) {
	if testing.Short() {
		t.Skip("skipping in short mode")
	}
	i := 0
	for i < randomChecks {
		a1 := math.Float32frombits(randomUint32())
		a2 := math.Float32frombits(randomUint32())

		if math.IsNaN(float64(a1)) || math.IsNaN(float64(a2)) {
			continue
		}
		i++

		r1 := make([]byte, 4)
		PutFloat32(r1, a1)
		v1 := Float32(r1)
		assert.Equal(t, a1, v1)

		r2 := make([]byte, 4)
		PutFloat32(r2, a2)

		switch {
		case a1 < a2:
			assert.Equal(t, -1, bytes.Compare(r1, r2), "%v %v", a1, a2)
		case a1 == a2:
			assert.Equal(t, 0, bytes.Compare(r1, r2), "%v %v", a1, a2)
		case a1 > a2:
			assert.Equal(t, +1, bytes.Compare(r1, r2), "%v %v", a1, a2)
		}
	}
}
func (u *UseEntity) read(rr io.Reader) (err error) {
	var tmp [4]byte
	if u.TargetID, err = ReadVarInt(rr); err != nil {
		return
	}
	if u.Type, err = ReadVarInt(rr); err != nil {
		return
	}
	if u.Type == 2 {
		var tmp0 uint32
		if _, err = rr.Read(tmp[:4]); err != nil {
			return
		}
		tmp0 = (uint32(tmp[3]) << 0) | (uint32(tmp[2]) << 8) | (uint32(tmp[1]) << 16) | (uint32(tmp[0]) << 24)
		u.TargetX = math.Float32frombits(tmp0)
		var tmp1 uint32
		if _, err = rr.Read(tmp[:4]); err != nil {
			return
		}
		tmp1 = (uint32(tmp[3]) << 0) | (uint32(tmp[2]) << 8) | (uint32(tmp[1]) << 16) | (uint32(tmp[0]) << 24)
		u.TargetY = math.Float32frombits(tmp1)
		var tmp2 uint32
		if _, err = rr.Read(tmp[:4]); err != nil {
			return
		}
		tmp2 = (uint32(tmp[3]) << 0) | (uint32(tmp[2]) << 8) | (uint32(tmp[1]) << 16) | (uint32(tmp[0]) << 24)
		u.TargetZ = math.Float32frombits(tmp2)
	}
	if u.Type == 0 || u.Type == 2 {
		if u.Hand, err = ReadVarInt(rr); err != nil {
			return
		}
	}
	return
}
Example #3
0
func (smp complexLEF32Sampler) Transform(buf []byte, data accel.DSPSplitComplex) {
	for i := 0; i < len(data.Real); i++ {
		j := i * 8
		data.Real[i] = math.Float32frombits(binary.LittleEndian.Uint32(buf[j : j+4]))
		data.Imag[i] = math.Float32frombits(binary.LittleEndian.Uint32(buf[j+4 : j+8]))
	}
}
Example #4
0
func (d *decoder) value(v reflect.Value) {
	switch v.Kind() {
	case reflect.Array:
		l := v.Len()
		for i := 0; i < l; i++ {
			d.value(v.Index(i))
		}

	case reflect.Struct:
		l := v.NumField()
		for i := 0; i < l; i++ {
			d.value(v.Field(i))
		}

	case reflect.Slice:
		l := v.Len()
		for i := 0; i < l; i++ {
			d.value(v.Index(i))
		}

	case reflect.Int8:
		v.SetInt(int64(d.int8()))
	case reflect.Int16:
		v.SetInt(int64(d.int16()))
	case reflect.Int32:
		v.SetInt(int64(d.int32()))
	case reflect.Int64:
		v.SetInt(d.int64())

	case reflect.Uint8:
		v.SetUint(uint64(d.uint8()))
	case reflect.Uint16:
		v.SetUint(uint64(d.uint16()))
	case reflect.Uint32:
		v.SetUint(uint64(d.uint32()))
	case reflect.Uint64:
		v.SetUint(d.uint64())

	case reflect.Float32:
		v.SetFloat(float64(math.Float32frombits(d.uint32())))
	case reflect.Float64:
		v.SetFloat(math.Float64frombits(d.uint64()))

	case reflect.Complex64:
		v.SetComplex(complex(
			float64(math.Float32frombits(d.uint32())),
			float64(math.Float32frombits(d.uint32())),
		))
	case reflect.Complex128:
		v.SetComplex(complex(
			math.Float64frombits(d.uint64()),
			math.Float64frombits(d.uint64()),
		))
	}
}
Example #5
0
func complex64Decoder(dec *decoder, v reflect.Value) error {
	bs := dec.buf[:8]
	if err := readAtLeast(dec, bs, 8); err != nil {
		return err
	}
	v.SetComplex(complex(
		float64(math.Float32frombits(dec.order.Uint32(bs))),
		float64(math.Float32frombits(dec.order.Uint32(bs[4:]))),
	))
	return nil
}
Example #6
0
func complex64Decoder(dec *decoder, p unsafe.Pointer) error {
	bs := dec.buf[:8]
	if err := readAtLeast(dec, bs, 8); err != nil {
		return err
	}
	v := (*complex64)(p)
	*v = complex(
		math.Float32frombits(dec.order.Uint32(bs)),
		math.Float32frombits(dec.order.Uint32(bs[4:])),
	)
	return nil
}
Example #7
0
func handleConnection(conn net.Conn) {
	player := &Player{Conn: conn}
	defer func() {
		log.Printf("Player %q left (%s)\n", player.Nick, conn.RemoteAddr())
		mu.Lock()
		game.Leave(player)
		mu.Unlock()
	}()

	var nickLength uint32
	binary.Read(conn, binary.BigEndian, &nickLength)
	nickBytes := make([]byte, nickLength)
	if _, err := io.ReadFull(conn, nickBytes); err != nil {
		log.Println(err)
		return
	}
	player.Nick = string(nickBytes)

	mu.Lock()
	game.Join(player, 200, 200)
	mu.Unlock()

	log.Printf("Player %q joined (%s)\n", player.Nick, conn.RemoteAddr())

	buf := make([]byte, 12)
	for {
		if _, err := io.ReadFull(conn, buf); err != nil {
			if err != io.EOF {
				log.Println(err)
			}
			return
		}
		mu.Lock()
		player.JoystickX = math.Float32frombits(binary.BigEndian.Uint32(buf))
		player.JoystickY = math.Float32frombits(binary.BigEndian.Uint32(buf[4:]))
		buttons := binary.BigEndian.Uint32(buf[8:])
		player.ButtonA = buttons&1 != 0
		player.ButtonB = buttons&2 != 0
		if player.JoystickX < -1 {
			player.JoystickX = -1
		} else if player.JoystickX > 1 {
			player.JoystickX = 1
		}
		if player.JoystickY < -1 {
			player.JoystickY = 1
		} else if player.JoystickY > 1 {
			player.JoystickY = 1
		}
		mu.Unlock()
	}
}
Example #8
0
func (p *Parser) ReadFloat32(value *float32) *Parser {
	bufFloat32 := make([]byte, 4)
	if bufFloat32 = p.buffer.Next(4); len(bufFloat32) < 4 {
		p.err = errors.New("Not enough bytes in buffer")
		return p
	}

	if p.Endian() == BigEndian {
		(*value) = math.Float32frombits(binary.BigEndian.Uint32(bufFloat32))
	} else {
		(*value) = math.Float32frombits(binary.LittleEndian.Uint32(bufFloat32))
	}

	return p
}
Example #9
0
func (d *simpleDecDriver) decodeFloat(chkOverflow32 bool) (f float64) {
	switch d.bd {
	case simpleVdFloat32:
		f = float64(math.Float32frombits(d.r.readUint32()))
	case simpleVdFloat64:
		f = math.Float64frombits(d.r.readUint64())
	default:
		if d.bd >= simpleVdPosInt1 && d.bd <= simpleVdNegInt8 {
			_, i, _ := d.decIntAny()
			f = float64(i)
		} else {
			decErr("Float only valid from float32/64: Invalid descriptor: %v", d.bd)
		}
	}
	// check overflow (logic adapted from std pkg reflect/value.go OverflowFloat()
	if chkOverflow32 {
		f2 := f
		if f2 < 0 {
			f2 = -f
		}
		if math.MaxFloat32 < f2 && f2 <= math.MaxFloat64 {
			decErr("Overflow float32 value: %v", f2)
		}
	}
	return
}
Example #10
0
func ReadFloat32(buf []byte, format byte, endianness binary.ByteOrder) float32 {
	encoding := format & EncodingMask

	if encoding == EncodingFloatingPoint {
		return math.Float32frombits(endianness.Uint32(buf))
	} else {
		offset := 0
		if endianness == binary.LittleEndian {
			offset = len(buf) - 1
		}
		var neg byte = 0
		if encoding == EncodingSignedInt && buf[offset]&(1<<7) != 0 {
			neg = 0xFF
		}
		tmp := []byte{neg, neg, neg, neg}

		if endianness == binary.BigEndian {
			copy(tmp[4-len(buf):], buf)
		} else {
			copy(tmp, buf)
		}

		sample := endianness.Uint32(tmp)

		div := math.Pow(2, float64(len(buf)*8-1))
		if encoding == EncodingSignedInt {
			return float32(float64(int32(sample)) / div)
		} else {
			return float32(float64(sample)/div - 1.0)
		}
	}
}
Example #11
0
func TestFloat32(t *testing.T) {
	var buf = make([]byte, 4)
	var expected = float32(2 << 15)

	// Put
	bytes, err := LittleEndian.PutFloat32(buf, 0, expected)
	assert.Nil(t, err)
	assert.Equal(t, expected, math.Float32frombits(binary.LittleEndian.Uint32(buf)))
	assert.Equal(t, uint64(4), bytes)

	// Put error (index = -1)
	bytes, err = LittleEndian.PutFloat32(buf, -1, expected)
	assert.NotNil(t, err)
	assert.Equal(t, uint64(0), bytes)

	// Put error (index = 2)
	bytes, err = LittleEndian.PutFloat32(buf, 2, expected)
	assert.NotNil(t, err)
	assert.Equal(t, uint64(0), bytes)

	// Get
	val, err := LittleEndian.Float32(buf, 0)
	assert.Nil(t, err)
	assert.Equal(t, expected, val)

	// Get Error (index = -1)
	val, err = LittleEndian.Float32(buf, -1)
	assert.NotNil(t, err)
	assert.Equal(t, float32(0), val)

	// Get Error (index = 2)
	val, err = LittleEndian.Float32(buf, 2)
	assert.NotNil(t, err)
	assert.Equal(t, float32(0), val)
}
Example #12
0
// TestRoundTrip32 tries a fraction of all finite positive float32 values.
func TestRoundTrip32(t *testing.T) {
	step := uint32(997)
	if testing.Short() {
		step = 99991
	}
	count := 0
	for i := uint32(0); i < 0xff<<23; i += step {
		f := math.Float32frombits(i)
		if i&1 == 1 {
			f = -f // negative
		}
		s := FormatFloat(float64(f), 'g', -1, 32)

		parsed, err := ParseFloat(s, 32)
		parsed32 := float32(parsed)
		switch {
		case err != nil:
			t.Errorf("ParseFloat(%q, 32) gave error %s", s, err)
		case float64(parsed32) != parsed:
			t.Errorf("ParseFloat(%q, 32) = %v, not a float32 (nearest is %v)", s, parsed, parsed32)
		case parsed32 != f:
			t.Errorf("ParseFloat(%q, 32) = %b (expected %b)", s, parsed32, f)
		}
		count++
	}
	t.Logf("tested %d float32's", count)
}
Example #13
0
func decodeFloat4(vr *ValueReader) float32 {
	if vr.Len() == -1 {
		vr.Fatal(ProtocolError("Cannot decode null into float32"))
		return 0
	}

	if vr.Type().DataType != Float4Oid {
		vr.Fatal(ProtocolError(fmt.Sprintf("Cannot decode oid %v into float32", vr.Type().DataType)))
		return 0
	}

	switch vr.Type().FormatCode {
	case TextFormatCode:
		s := vr.ReadString(vr.Len())
		n, err := strconv.ParseFloat(s, 32)
		if err != nil {
			vr.Fatal(ProtocolError(fmt.Sprintf("Received invalid float4: %v", s)))
			return 0
		}
		return float32(n)
	case BinaryFormatCode:
		if vr.Len() != 4 {
			vr.Fatal(ProtocolError(fmt.Sprintf("Received an invalid size for an float4: %d", vr.Len())))
			return 0
		}

		i := vr.ReadInt32()
		return math.Float32frombits(uint32(i))
	default:
		vr.Fatal(ProtocolError(fmt.Sprintf("Unknown field description format code: %v", vr.Type().FormatCode)))
		return 0
	}
}
Example #14
0
// Float32 converts the 8-bit floating-point value to a float32. The 8-bit and
// the 32-bit floating-point notation formats are described at Float8 and New
// respectively.
func (f Float8) Float32() float32 {
	if f == 0 {
		// Return the floating-point value 0.
		return 0
	}

	// bits is the bit representation of the float32 value.
	var bits uint32

	// Sign bit.
	if f.Sign() {
		bits |= 0x80000000
	}

	// Exponent.
	exp := f.Exp()
	exp-- // adjust exponent for the implicit 1.

	// Encode exponent.
	xexp := uint8(exp)
	xexp += 127 // excess 127 notation.
	bits |= uint32(xexp) << 23

	// Mantissa.
	mantissa := f.Mantissa()
	// remove the implicit 1 from the mantissa.
	mantissa &^= 0x8

	// Encode the mantissa.
	bits |= uint32(mantissa) << 20

	return math.Float32frombits(bits)
}
Example #15
0
// read/write float32.
func (ps *PacketSerializer) readFloat32(reader io.Reader) (v float32, err error) {
	var vUint32 uint32
	if vUint32, err = ps.readUint32(reader); err != nil {
		return
	}
	return math.Float32frombits(vUint32), nil
}
Example #16
0
func decode(b []byte, t uint16) driver.Value {
	switch t {
	case typeBool:
		if len(b) >= 1 && b[0] != 0 {
			return true
		}
		return false
	case typeBlob:
		return b
	case typeVarchar, typeText, typeAscii:
		return b
	case typeInt:
		return int64(int32(binary.BigEndian.Uint32(b)))
	case typeBigInt:
		return int64(binary.BigEndian.Uint64(b))
	case typeFloat:
		return float64(math.Float32frombits(binary.BigEndian.Uint32(b)))
	case typeDouble:
		return math.Float64frombits(binary.BigEndian.Uint64(b))
	case typeTimestamp:
		t := int64(binary.BigEndian.Uint64(b))
		sec := t / 1000
		nsec := (t - sec*1000) * 1000000
		return time.Unix(sec, nsec)
	case typeUUID, typeTimeUUID:
		return uuid.FromBytes(b)
	default:
		panic("unsupported type")
	}
	return b
}
Example #17
0
func (s *Sprite) SetTint(tint uint32) {
	r := uint32((tint >> 16) & 0xFF)
	g := uint32((tint >> 8) & 0xFF)
	b := uint32(tint & 0xFF)
	a := uint32(s.Alpha * 255.0)
	s.color = math.Float32frombits((a<<24 | b<<16 | g<<8 | r) & 0xfeffffff)
}
Example #18
0
func (rs *ResultSet) float32(ord int) (value float32, isNull bool) {
	if rs.conn.LogLevel >= LogVerbose {
		defer rs.conn.logExit(rs.conn.logEnter("*ResultSet.float32"))
	}

	isNull = rs.isNull(ord)
	if isNull {
		return
	}

	val := rs.values[ord]

	switch rs.fields[ord].format {
	case textFormat:
		// strconv.Atof32 does not handle NaN
		if string(val) == "NaN" {
			value = float32(math.NaN())
		} else {
			var err os.Error
			value, err = strconv.Atof32(string(val))
			panicIfErr(err)
		}

	case binaryFormat:
		value = math.Float32frombits(binary.BigEndian.Uint32(val))
	}

	return
}
Example #19
0
// Decode will take the binary data and decode into
// into the ensemble data set.
func (vel *EarthVelocityDataSet) Decode(data []byte) {

	// Initialize the 2D array
	// [Bins][Beams]
	vel.Velocity = make([][]float32, vel.Base.NumElements)
	for i := range vel.Velocity {
		vel.Velocity[i] = make([]float32, vel.Base.ElementMultiplier)
	}
	vel.Vectors = make([]VelocityVector, vel.Base.NumElements)

	// Not enough data
	if uint32(len(data)) < vel.Base.NumElements*vel.Base.ElementMultiplier*uint32(BytesInFloat) {
		return
	}

	// Set each beam and bin data
	ptr := 0
	for beam := 0; beam < int(vel.Base.ElementMultiplier); beam++ {
		for bin := 0; bin < int(vel.Base.NumElements); bin++ {
			// Get the location of the data
			ptr = GetBinBeamIndex(int(vel.Base.NameLen), int(vel.Base.NumElements), beam, bin)

			// Set the data to float
			bits := binary.LittleEndian.Uint32(data[ptr : ptr+BytesInFloat])
			vel.Velocity[bin][beam] = math.Float32frombits(bits)

			// Calculate the velocity vector
			vel.Vectors[bin] = calcVV(vel.Velocity[bin])
		}
	}
}
Example #20
0
// Value returns the field's value as interface{}.
func (lf Field) Value() interface{} {
	switch lf.fieldType {
	case stringType:
		return lf.stringVal
	case boolType:
		return lf.numericVal != 0
	case intType:
		return int(lf.numericVal)
	case int32Type:
		return int32(lf.numericVal)
	case int64Type:
		return int64(lf.numericVal)
	case uint32Type:
		return uint32(lf.numericVal)
	case uint64Type:
		return uint64(lf.numericVal)
	case float32Type:
		return math.Float32frombits(uint32(lf.numericVal))
	case float64Type:
		return math.Float64frombits(uint64(lf.numericVal))
	case errorType, objectType, lazyLoggerType:
		return lf.interfaceVal
	default:
		return nil
	}
}
Example #21
0
// Marshal passes a Field instance through to the appropriate
// field-type-specific method of an Encoder.
func (lf Field) Marshal(visitor Encoder) {
	switch lf.fieldType {
	case stringType:
		visitor.EmitString(lf.key, lf.stringVal)
	case boolType:
		visitor.EmitBool(lf.key, lf.numericVal != 0)
	case intType:
		visitor.EmitInt(lf.key, int(lf.numericVal))
	case int32Type:
		visitor.EmitInt32(lf.key, int32(lf.numericVal))
	case int64Type:
		visitor.EmitInt64(lf.key, int64(lf.numericVal))
	case uint32Type:
		visitor.EmitUint32(lf.key, uint32(lf.numericVal))
	case uint64Type:
		visitor.EmitUint64(lf.key, uint64(lf.numericVal))
	case float32Type:
		visitor.EmitFloat32(lf.key, math.Float32frombits(uint32(lf.numericVal)))
	case float64Type:
		visitor.EmitFloat64(lf.key, math.Float64frombits(uint64(lf.numericVal)))
	case errorType:
		visitor.EmitString(lf.key, lf.interfaceVal.(error).Error())
	case objectType:
		visitor.EmitObject(lf.key, lf.interfaceVal)
	case lazyLoggerType:
		visitor.EmitLazyLogger(lf.interfaceVal.(LazyLogger))
	}
}
Example #22
0
func readFixedType(ti *typeInfo, r *tdsBuffer) (res interface{}) {
	r.ReadFull(ti.Buffer)
	buf := ti.Buffer
	switch ti.TypeId {
	case typeNull:
		return nil
	case typeInt1:
		return int64(buf[0])
	case typeBit:
		return buf[0] != 0
	case typeInt2:
		return int64(int16(binary.LittleEndian.Uint16(buf)))
	case typeInt4:
		return int64(int32(binary.LittleEndian.Uint32(buf)))
	case typeDateTim4:
		return decodeDateTim4(buf)
	case typeFlt4:
		return math.Float32frombits(binary.LittleEndian.Uint32(buf))
	case typeMoney4:
		return decodeMoney4(buf)
	case typeMoney:
		return decodeMoney(buf)
	case typeDateTime:
		return decodeDateTime(buf)
	case typeFlt8:
		return math.Float64frombits(binary.LittleEndian.Uint64(buf))
	case typeInt8:
		return int64(binary.LittleEndian.Uint64(buf))
	default:
		badStreamPanicf("Invalid typeid")
	}
	panic("shoulnd't get here")
}
Example #23
0
// read will read a single entry from the BOW database.
//
// It would be much nicer to use the binary package here (like we do for
// reading), but we need to be as fast here as possible. (It looks like
// there is a fair bit of allocation going on in the binary package.)
// Benchmarks are gone in the wind...
func (db *DB) read() (*bow.Bowed, error) {

	// Read in the id string.
	if err := db.readItem(); err != nil {
		return nil, err
	}
	id := string(db.entryBuf)

	// Read in the arbitrary data.
	if err := db.readItem(); err != nil {
		return nil, err
	}
	data := db.newData(len(db.entryBuf))
	copy(data, db.entryBuf)

	// Now read in the BOW.
	if err := db.readItem(); err != nil {
		return nil, err
	}

	freqs := db.newBow()
	// Advance 6 bytes at a time. 2 bytes for the fragment index and
	// 4 bytes for the fragment frequency.
	for i := 0; i < len(db.entryBuf); i += 6 {
		fragi := binary.BigEndian.Uint16(db.entryBuf[i : i+2])
		freqs[fragi] = math.Float32frombits(
			binary.BigEndian.Uint32(db.entryBuf[i+2 : i+6]))
	}
	return &bow.Bowed{Id: id, Data: data, Bow: bow.Bow{freqs}}, nil
}
Example #24
0
func (p *binReader) readFloat32() (x float32, err error) {
	code, err := p.decodeFixed32()
	if err != nil {
		return
	}
	return math.Float32frombits(code), nil
}
Example #25
0
// sampleValueAtIndex implements chunkIterator.
func (it *deltaEncodedChunkIterator) sampleValueAtIndex(idx int) clientmodel.SampleValue {
	offset := deltaHeaderBytes + idx*int(it.tBytes+it.vBytes) + int(it.tBytes)

	if it.isInt {
		switch it.vBytes {
		case d0:
			return it.baseV
		case d1:
			return it.baseV + clientmodel.SampleValue(int8(it.c[offset]))
		case d2:
			return it.baseV + clientmodel.SampleValue(int16(binary.LittleEndian.Uint16(it.c[offset:])))
		case d4:
			return it.baseV + clientmodel.SampleValue(int32(binary.LittleEndian.Uint32(it.c[offset:])))
		// No d8 for ints.
		default:
			panic("Invalid number of bytes for integer delta")
		}
	} else {
		switch it.vBytes {
		case d4:
			return it.baseV + clientmodel.SampleValue(math.Float32frombits(binary.LittleEndian.Uint32(it.c[offset:])))
		case d8:
			// Take absolute value for d8.
			return clientmodel.SampleValue(math.Float64frombits(binary.LittleEndian.Uint64(it.c[offset:])))
		default:
			panic("Invalid number of bytes for floating point delta")
		}
	}
}
Example #26
0
func (dec *Decoder) parseHeader() (version string, tempo float32) {
	if dec.err != nil {
		return
	}

	buffer := make([]byte, 50)
	n, err := dec.r.Read(buffer)

	if err != nil {
		dec.err = err
		return
	}

	if n < 50 {
		dec.err = ErrSmallBinary
		return
	}

	// Validate the binary header
	for i := 0; i < len(SPLICE); i++ {
		if SPLICE[i] != buffer[i] {
			dec.err = ErrInValidHeader
			return
		}
	}

	dec.len = int(binary.BigEndian.Uint32(buffer[10:14]))
	version = string(bytes.Trim(buffer[14:46], "\x00"))
	tempo = math.Float32frombits(binary.LittleEndian.Uint32(buffer[46:50]))
	dec.len = dec.len - 36
	return
}
Example #27
0
// Set sets p to point at a newly allocated word with bits set to x.
func word32_Set(p word32, o *Buffer, x uint32) {
	t := p.v.Type().Elem()
	switch t {
	case int32Type:
		if len(o.int32s) == 0 {
			o.int32s = make([]int32, uint32PoolSize)
		}
		o.int32s[0] = int32(x)
		p.v.Set(reflect.ValueOf(&o.int32s[0]))
		o.int32s = o.int32s[1:]
		return
	case uint32Type:
		if len(o.uint32s) == 0 {
			o.uint32s = make([]uint32, uint32PoolSize)
		}
		o.uint32s[0] = x
		p.v.Set(reflect.ValueOf(&o.uint32s[0]))
		o.uint32s = o.uint32s[1:]
		return
	case float32Type:
		if len(o.float32s) == 0 {
			o.float32s = make([]float32, uint32PoolSize)
		}
		o.float32s[0] = math.Float32frombits(x)
		p.v.Set(reflect.ValueOf(&o.float32s[0]))
		o.float32s = o.float32s[1:]
		return
	}

	// must be enum
	p.v.Set(reflect.New(t))
	p.v.Elem().SetInt(int64(int32(x)))
}
Example #28
0
func (rs *ResultSet) float32(ord int) (value float32, isNull bool) {
	if rs.conn.LogLevel >= LogVerbose {
		defer rs.conn.logExit(rs.conn.logEnter("*ResultSet.float32"))
	}

	isNull = rs.isNull(ord)
	if isNull {
		return
	}

	val := rs.values[ord]

	switch rs.fields[ord].format {
	case textFormat:
		// strconv.Atof32 does not handle "-Infinity" and "Infinity"
		valStr := string(val)
		switch valStr {
		case "-Infinity":
			value = float32(math.Inf(-1))

		case "Infinity":
			value = float32(math.Inf(1))

		default:
			var err os.Error
			value, err = strconv.Atof32(valStr)
			panicIfErr(err)
		}

	case binaryFormat:
		value = math.Float32frombits(binary.BigEndian.Uint32(val))
	}

	return
}
Example #29
0
// Decode will take the binary data and decode into
// into the ensemble data set.
func (amp *AmplitudeDataSet) Decode(data []byte) {

	// Initialize the 2D array
	// [Bins][Beams]
	amp.Amplitude = make([][]float32, amp.Base.NumElements)
	for i := range amp.Amplitude {
		amp.Amplitude[i] = make([]float32, amp.Base.ElementMultiplier)
	}

	// Not enough data
	if uint32(len(data)) < amp.Base.NumElements*amp.Base.ElementMultiplier*uint32(BytesInFloat) {
		return
	}

	// Set each beam and bin data
	ptr := 0
	for beam := 0; beam < int(amp.Base.ElementMultiplier); beam++ {
		for bin := 0; bin < int(amp.Base.NumElements); bin++ {
			// Get the location of the data
			ptr = GetBinBeamIndex(int(amp.Base.NameLen), int(amp.Base.NumElements), beam, bin)

			// Set the data to float
			bits := binary.LittleEndian.Uint32(data[ptr : ptr+BytesInFloat])
			amp.Amplitude[bin][beam] = math.Float32frombits(bits)
		}
	}

}
Example #30
0
func (cursor *Cursor) interpretBytesAsTime(data []byte) time.Time {
	integer := cursor.interpretBytesAsInteger(data)
	var date_time time.Time
	if cursor.mode == IntegerMode {
		if cursor.epoch_unit == SecondsSinceEpoch {
			date_time = cursor.epoch_time.Add(time.Duration(integer) * time.Second)
		} else if cursor.epoch_unit == DaysSinceEpoch {
			date_time = cursor.epoch_time.Add(time.Duration(integer) * 24 * time.Hour)
		}
	} else if cursor.mode == FloatingPointMode {
		var float float64
		if cursor.fp_length == 4 {
			float = float64(math.Float32frombits(uint32(integer)))
		} else {
			float = math.Float64frombits(integer)
		}
		if cursor.epoch_unit == SecondsSinceEpoch {
			date_time = cursor.epoch_time.Add(time.Duration(float * float64(time.Second)))
		} else {
			date_time = cursor.epoch_time.Add(time.Duration(float * 24 * float64(time.Hour)))
		}
	} else {
		date_time = cursor.epoch_time
	}
	return date_time.UTC()
}