알뜰살뜰 정보/Node

byte 관련

쉬고싶은 거북이 2021. 2. 23. 16:13

 

/**

 * file   : utils.ts

  * brief  : user function collection.

**/



export class Utils {

    constructor() {}

    /**

     * hex --> 2-digit ascii

     */

    public hex2ascii(value: number, size: number): number[] {

        const arr = []

        let str = value.toString(16)

        if (str.length > size) {

            throw new Error('ddd')

        }

        str = '0'.repeat(size - str.length) + str

        for (let i = 0, l = str.length; i < l; i++) {

            const hex = Number(str.charCodeAt(i)) // .toString(16)

            arr.push(hex)

        }

        return arr // .join('')

    }



    /**

     * ascii --> 1-digit hex 

     */

    public hex_to_ascii(str1: any) {

       var hex  = str1.toString();

       var str = '';

       for (var n = 0; n < hex.length; n += 2) {

           str += String.fromCharCode(parseInt(hex.substr(n, 2), 16));

       }

       return str;

    }



    /**

     * ascii --> 2-digit hex 

     */

    public ascii2hex(arr: number[]) {

        const hex = Array.from(arr, (byte) => {

            return ('0' + (byte & 0xff).toString(16)).slice(-2)

        }).join('')

    // -> Byte array to Hex string conversion in javascript

        let str = ''

        for (let i = 0; i < hex.length && hex.substr(i, 2) !== '00'; i += 2) {

            str += String.fromCharCode(parseInt(hex.substr(i, 2), 16))

        }

    // -> javascript 16진수 문자열 -> ASCII code 문자열

        // console.log(str)



        const ret = parseInt(str, 16)   //문자열을 정수로

        try {

            if (isNaN(ret)) {

                throw new Error('Invalid Value')

            }

            // console.log(ret)

        } catch(e) {

            console.log('isNaN false')

        }

        return ret

    }

    /**

     * Checksum function is the same, but not available for array 

     */

    public sum(arr: number[]):number {

        let sum = 0

        arr.forEach(element => {

            sum += element

        });

        // console.log(sum)

        return sum

    }

    /**

     * array values += value

     */

    public checkSum(data: number[], startIdx?: number, endIdx?: number): number {

        const start = startIdx ? startIdx : 0

        const end = endIdx ? endIdx : data.length

        let sum = 0

        



        for (let index = start; index < end; index++) {

            const element = Number(data[index])

            sum += element

        }

        return sum

    

    }

    /**

     * array values ^= value 

     */

       public calcCRC(data: number[], startIdx?: number, endIdx?: number): number {

        const start = startIdx ? startIdx : 0

        const end = endIdx ? endIdx : data.length

        let sum = 0

        



        for (let index = start; index < end; index++) {

            const element = data[index]

            sum ^= element

        }

        return sum

    

    }

    /**

     * get mac but don't use

     */

    public getmac(): Promise<number> {

        return new Promise((resolve, reject) => {

            require('getmac').getMac((err: any, macAddress: any) => {

                if (err) {

                    reject(err)

                }

                console.log(macAddress)



                resolve(parseInt(macAddress.replace(/:/g, ''), 16))

            })

        })

    }

    /**

     * Dec --> toHex 

     */

    public toHex(arr:any) {

        var x = ''    

        arr.forEach((val:any) => {        

            x += val.toString(16) + ' ';

        });

        

        return x;

    }

    /**

     * array value --> crc1 

     */

    public crc1(crc: number[]) {

        let hexSUM = 0;

        crc.forEach(element => {

            hexSUM += element;

        });

        const checkSUM = (0xff & hexSUM);



        return checkSUM

    }

    /**

     * hex 0x14 --> arr[1] + arr[4] = (String)14

     */

    public hex2String(val: any) {

        const arr = []

        arr[0] = (val >> 4) & 0x0F;

        arr[1] = val & 0x0F;



        if(arr[0] >= 10) {

            arr[0] = arr[0] - 10 + 'A';

        }

        else {

            arr[0] = arr[0] + '0'

        }

        // console.log('arr[0] :', arr[0], 'arr[1] :', arr[1])

        const sum = Number(arr[0]) + Number(arr[1])

        return sum

    }



    public hex256Sum(data: any, start: number, end: number) {

        let sum = 0;

        for (let index = start ; index < end; index++) {            

            if(sum != 0) {

                sum = sum * 256 + data[index]

            } else {

                sum = data[index];

            }

        }



        return sum

    }




}