I'm far from being a MySql expert, in fact I have never written 'a stored procedure', which might be what I need here.
What I have: A (up to ) 128 bit integer - as a string (it's actually an Ipv6 address).
What I want : A MySql varbinary(16) value.
I'm trying to convert a 128 bit integer, so it can be stored in MySql as varbinary(16).
From what I know, the only type in MySql, that can handle such a big integer is the decimal
data type.
However there seems to be no conversions from decimal
to either hex string or varbinary
. I want to use varbinary(16)
for 2 reasons:
- It's the most compact.
- Both MySql and C# can directly create Ipv6 addresses from this format. And the opposite is easy too.
I have tried several (miserable) attempts with 'CAST', 'HEX' and ip conversion functions. They don't seem to work with Decimal
.
However, I managed to create this query in C#, that works, but is slow:
string value1 = "281470698520576"; // example1 (less than 128 bit - must be leftpadded with zeros).
string value2 = "42541870534966271977089220242718064640"; // example2 (128 bit)
StringBuilder sb = new StringBuilder("INSERT INTO ......... VALUES");
sb.Append("(").Append("UNHEX('").Append(BigInteger.Parse(value1).ToString("x32")).Append("'), ")
.Append("UNHEX('").Append(BigInteger.Parse(value2 ).ToString("x32")).Append("')");
I would prefer to 'do it in MySql' since that's normally faster, but I can use any combination of C#/MySql - may be a stored procedure.
Is there a way to do it in MySql?