1 /** 2 * Copyright 2020 Huawei Technologies Co., Ltd 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 #include "nnacl/nnacl_common.h" 18 19 typedef union float32_bits { 20 unsigned int u; 21 float f; 22 } float32_bits; 23 ShortToFloat32(uint16_t src_value)24float ShortToFloat32(uint16_t src_value) { 25 const float32_bits magic = {113 << 23}; 26 const unsigned int shifted_exp = 0x7c00 << 13; 27 float32_bits o; 28 29 o.u = (src_value & 0x7fff) << 13; 30 unsigned int exp = shifted_exp & o.u; 31 o.u += (127 - 15) << 23; 32 33 if (exp == shifted_exp) { 34 o.u += (128 - 16) << 23; 35 } else if (exp == 0) { 36 o.u += 1 << 23; 37 o.f -= magic.f; 38 } 39 40 o.u |= (src_value & 0x8000) << 16; 41 return o.f; 42 } 43 Float32ToShort(float src_value)44uint16_t Float32ToShort(float src_value) { 45 float32_bits src_value_bits; 46 src_value_bits.f = src_value; 47 uint16_t res = 0; 48 // mantissa 49 res += (src_value_bits.u >> 13); 50 // exponent 51 res += (src_value_bits.u >> 13) & 0x3fc00; 52 res -= (127 - 15) << 13; 53 54 // sign 55 res |= (src_value_bits.u & 0x80000000) >> 16; 56 return res; 57 } 58