Skip to content

Request to Add Function for Converting Two's Complement HEX to Decimal (Support for Multi-byte Length) #40

@volodymyr-babak

Description

@volodymyr-babak

Currently, there is no built-in function in TBEL to convert Two's Complement HEX values to Decimal.
I would like to propose adding a function that supports this conversion, specifically for HEX values with multiple bytes in length.

As a starting point, I've provided a sample code that is capable of converting a single byte HEX value to a Decimal number.
This sample was developed by @rekcaiot and currently only handles single-byte conversions, but the goal is to expand this functionality to support multiple-byte HEX values.

Here’s the sample code that works for converting single byte HEX to Decimal:

function twoComplementOneByte(hex){
    var signed = parseInt(hex,16) & 0x80; //is first bit signed? 0 = positive number; >0 = negative number
    if(signed > 0){
        var binaryString = Integer.toString(parseInt(hex, 16), 2);  //convert hex to binary string
        var binaryStringInverted = "";
        for(var k=0; k<binaryString.length; k++){  //invert all bits of string
            if(binaryString[k] == "0"){
                binaryStringInverted = binaryStringInverted + "1";
            }else{
                binaryStringInverted = binaryStringInverted + "0";
            }
        }
        return (parseInt(binaryStringInverted, 2) + 1) * -1;
    }else{
        return parseInt(hex, 16);
    }
}

Output:

0xDB -> -37 // 11011011
0x69 -> 105 // 01101001
0xF2 -> -14 // 11110010
0x9C -> -100 // 10011100
0x57 -> 87 // 01010111

Image

Results can be double checked here:
https://sandbox.mc.edu/~bennet/cs110/tc/tctod.html

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions