ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • js unsigned to signed integer
    카테고리 없음 2021. 8. 12. 18:33

    디코딩 과정 중 온도 정보값이 음수가 될 수 있다는 것을 고려해 signed int로 바꿔줘야 했다.

    하드웨어 단의 코드부터 signed 비트도 그냥 unsigned 배열에 담아서 보냈기 때문에 받은 다음 바꿔줘야 한다.

    var base_str = msg.frm_payload;
    var len = 32;
    var buffer = new ArrayBuffer(len);
    var view = new Uint16Array(buffer);
    for (var i = 0; i < len; i++){
        view[i] = base_str.charCodeAt(i);
    }
    msg.payload = view;
    return msg;

    일단 위와 같이 데이터를 받아올 때는 unsigned로 받아오고

    var view = msg.payload;
    //view[] = array of data packets
    
    //converting parted data packets to one
    //data comes as two integers, convert them into hexadecimal first.
    //concatenate two hex values (first half + second half)
    //and then convert it to integer again
    function U_convert(h1, h2){//unsigned version
        var hex_h1 = h1.toString(16);//first half
        var hex_h2 = h2.toString(16);//second half
        var hex_h1h2 = hex_h1 + hex_h2;//concat
        var Uint_h1h2 = parseInt(hex_h1h2, 16);
        return Uint_h1h2;
    }
    
    function convert(h1, h2){//signed version - for temperature
        var hex_h1 = h1.toString(16);//first half
        var hex_h2 = h2.toString(16);//second half
        var hex_h1h2 = hex_h1 + hex_h2;//concat
        var sign = parseInt(hex_h1h2, 16) & 0x8000;//check if MSB is 1
        if(sign > 0){ //if 1, it is negative
            return parseInt(hex_h1h2, 16) - 0x10000;
        }
        return parseInt(hex_h1h2, 16); //if positive
    }

    본격적으로 디코딩할때 signed와 unsigned를 나누어서 한다.

     

    참고: https://stackoverflow.com/questions/13468474/javascript-convert-a-hex-signed-integer-to-a-javascript-value 

Designed by Tistory.