question

JavaMan avatar image
JavaMan asked

Java 'Unhash' as T-SQL?

Mike Arney wrote a nice little hashcode function in T-SQL.

Could someone convert this java unhash code into T-SQL to complete the set...?

public static String unhash(int target) {
    StringBuilder unhashed = new StringBuilder();
    if (target < 0) {
        // String with hash of Integer.MIN_VALUE, 0x80000000
        unhashed.append("\u0915\u0009\u001e\u000c\u0002");
        if (target == Integer.MIN_VALUE)
            return unhashed.toString();
        // Find target without sign bit set
        target = target & Integer.MIN_VALUE;
    }
    unhash0(unhashed, target);
    return unhashed.toString();
}

private static void unhash0(StringBuilder partial, int target) {
    int div = target / 31;
    int rem = target % 31;

    if (div <= Character.MAX_VALUE) {
        if (div != 0)
            partial.append((char) div);
        partial.append((char) rem);
    } else {
        unhash0(partial, div);
        partial.append((char) rem);
    }
}
t-sqlscript
2 comments
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Grant Fritchey avatar image Grant Fritchey ♦♦ commented ·
To recreate a hash system like this, you'd be better off using CLR and calling that from TSQL, rather than trying to force this through TSQL.
1 Like 1 ·
TimothyAWiseman avatar image TimothyAWiseman commented ·
I'm with Grant. This could be done in SQL, but you are much better off writing something like this in C# and importing it as CLR.
0 Likes 0 ·
Fatherjack avatar image
Fatherjack answered

I expect so .

3 comments
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Grant Fritchey avatar image Grant Fritchey ♦♦ commented ·
Excellent! One of the best answers I've seen in a while.
1 Like 1 ·
JavaMan avatar image JavaMan commented ·
Thanks Fatherjack, accurate but not very helpful!
0 Likes 0 ·
Fatherjack avatar image Fatherjack ♦♦ commented ·
@JavaMan, sorry, couldn't resist! Its a hot, tired Friday afternoon here. I think Grant has answered the question for you though, its not something suited to TSQL, much better using CLR
0 Likes 0 ·
Jeff Moden avatar image
Jeff Moden answered

I'm not a C programmer so I don't actually know what the original code does. If someone could come up with an explanation of what is being done by the code, I'll take a crack at it just because it might be fun.

10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Write an Answer

Hint: Notify or tag a user in this post by typing @username.

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.