js將4個字節型字符串轉爲Float

function convertFloat(byteStr) {
        var buffer = str2ArrayBuffer(byteStr, 4);
        var dataView = new DataView(buffer, 0, 4);
        return dataView.getFloat32(0);
    }

    // 字符串轉爲ArrayBuffer對象,參數爲字符串
    function str2ArrayBuffer(str, len) {
        var buf = new ArrayBuffer(len);
        var bufView = new Uint8Array(buf);
        for (var i = 0, strLen = str.length; i < strLen; i++) {
            bufView[i] = parseInt(str.substr(i * 2, 2), 16);
        }
        return buf;
    }

首先將字符串轉換爲ArrayBuffer對象數組,再根據DataView方法進行轉換數組

相關文章
相關標籤/搜索