How To [SQL] : Convert Binary String to Integer value

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 value
e.g. 11 => 3

SELECT  [dbo].[udf_binarytoINT]('1011011011110') -- 5854
SELECT [dbo].[udf_binarytoINT]('1111100111101111111') --511871

*/
CREATE FUNCTION  [dbo].[UDF_BinarytoInt](@binarystring NVARCHAR(100))
RETURNS INT
AS
BEGIN

DECLARE @position INT, @rev NVARCHAR(100), @intvalue INT
-- Initialize the variables.
SET @position = 1
SET @rev = REVERSE(@binarystring)

DECLARE  @tbl table (powerv INT, bitvalue NVARCHAR(1)) 

--Split the individual bits (0/1) into seperate rows 
WHILE @position <= len(@rev)
   BEGIN
		INSERT INTO @tbl(powerv, bitvalue) 
		SELECT @position -1, SUBSTRING(@rev, @position, 1)
	    SET @position = @position + 1
   END

SELECT @intvalue = sum(power(2, powerv) * bitvalue) 
FROM @tbl
WHERE bitvalue > 0

RETURN @intvalue
END
GO

Until then, happy coding 🙂

Attributes, Properties and ViewState

Recently i was thinking on a rather a small but a niggling problem, as part of web control development, we save the information we need to be persisted in viewstate(this is rather obvious to state). The way i do it is as follows

   1:  public string ViewStatePropertyName
   2:          {
   3:              get
   4:              {
   5:                  //this is rather simplified version; we need to check null objects as well
   6:                  return (string)ViewState["ViewStatePropertyName"];
   7:              }
   8:              set
   9:              {
  10:                  ViewState["ViewStatePropertyName"] = value;
  11:              }
  12:          }

This works fine, but takes up a lot of space. So i was thinking on the lines of using the power of Attributes (MSDN : Attributes Tutorial). As i was wandering around i stumbled upon this article, which does pretty much the same thing what i wanted. Here is the link : Saving server control properties to ViewState with custom attributes.

 

I havent tried the example, will take a look once i have some little free space on my hand. Until then Happy Coding.