質問

Any good jscript code converter to C# I want to convert this piece of code into C# This code is for generating admin password base from device MAC Address

    <script language="jscript">
    var add=[12,2,17,5,16,31,28,10,16,20,22,1];
    var subst={58:122,59:121,60:120,61:119,62:118,63:117,64:116,91:115,92:114,93:113,94:112,45:111,96:110};

    function generatePassword(input){
    var inputMac=input.replace(/:/g,"").toUpperCase();
    var macPassword="";
if((inputMac.search(/^[A-F0-9]{12}$/)==-1) || (inputMac =="000000000000")){
    return macPassword="invalid"}
else{
    var b;
    var a;
    var c="";
    for(b=0;b<12;b++){
        a=inputMac.charCodeAt(b)+add[b];
        if(subst[a]){
            a=subst[a]
        }
        c+=String.fromCharCode(a)
    }
    return macPassword="2008"+c+"";
    }
};
</script>
役に立ちましたか?

解決

I don't know of any converters from JScript to C#, only the other way around. And I don't even have a very good opinion of those. IMO, there are too many language and framework specifics for "transpiling" to work really well.

I don't know where you found the code you posted, since based on the comments, you don't really know JScript. I hope you're better at C#, so that you'll at least understand the converted function:

public string GeneratePassword(string input)
{
    var add= new byte[] {12,2,17,5,16,31,28,10,16,20,22,1};
    var subst = new Dictionary<byte, byte> {{58,122},{59,121},{60,120},{61,119},{62,118},{63,117},{64,116},{91,115},{92,114},{93,113},{94,112},{45,111},{96,110}};

    var inputMac = input.Replace(":", "").ToUpperInvariant();
    if (!Regex.IsMatch(inputMac, "^[A-F0-9]{12}$") || (inputMac == "000000000000"))
    {
        return "invalid";
    }
    else
    {
        var c="";
        for(var b = 0; b < 12; b++)
        {
            var a = (byte)((byte)inputMac[b] + add[b]);
            if(subst.ContainsKey(a))
            {
                a=subst[a];
            }
            c += (char)a;
        }
        return "2008" + c;
    }
}

The C# code can be further improved, but I wanted to keep it as close to the original as possible, so that you can learn about the differences in specific constructs and do it yourself in the future, instead of just using the converted code as is.

Just curious: what are you going to use this function for?

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top