Recently i came across a very trivial but an interesting problem. The problem was how to convert a string representing a binary value to its corresponding integer value in SQL. I searched high and dry on the net, but was faced with no luck of finding an inbuilt method to accomplish the task.
So reluctantly i set out of doing it my own way. After a couple of false starts i came up with this solution. Pretty simple and elegant, more importantly effective.
/****** Object: UserDefinedFunction [dbo].[UDF_BinarytoInt] Script Date: 10/04/2010 20:47:36 ******/
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[UDF_BinarytoInt]') AND TYPE in (N'FN', N'IF', N'TF', N'FS', N'FT'))DROP FUNCTION [dbo].[UDF_BinarytoInt]GO/*
Converts a given binary string to a INTeger valuee.g. 11 => 3SELECT [dbo].[udf_binarytoINT]('1011011011110') -- 5854SELECT [dbo].[udf_binarytoINT]('1111100111101111111') --511871*/CREATE FUNCTION [dbo].[UDF_BinarytoInt](@binarystring NVARCHAR(100))RETURNS INTASBEGINDECLARE @position INT, @rev NVARCHAR(100), @intvalue INT-- Initialize the variables.
SET @position = 1SET @rev = REVERSE(@binarystring)DECLARE @tbl table (powerv INT, bitvalue NVARCHAR(1))--Split the individual bits (0/1) into seperate rows
WHILE @position <= len(@rev)BEGININSERT INTO @tbl(powerv, bitvalue)SELECT @position -1, SUBSTRING(@rev, @position, 1)SET @position = @position + 1ENDSELECT @intvalue = sum(power(2, powerv) * bitvalue)FROM @tblWHERE bitvalue > 0RETURN @intvalueENDGOUntil then, happy coding 🙂