Number functions

chm.ToBinaryString

This function converts an integer to binary.

      CREATE FUNCTION [chm].[ToBinaryString]
(
    @num       BIGINT,
    @length    TINYINT
)
RETURNS NVARCHAR (MAX)
    

If @length is greater than zero, it is assumed as the total size of the resulted binary string with extra zeros appended from the left. Example:

      select chm.ToBinaryString(23, 0)	--    10111
select chm.ToBinaryString(23, 8)	-- 00010111
    

chm.FromBinaryString

This function converts a binary string to an integer.

      CREATE FUNCTION [chm].[FromBinaryString]
(
    @binary NVARCHAR(MAX)
)
RETURNS BIGINT
    

Note: Invalid characters (non-zeo or 1) are assumed as zero.

Example:

      select chm.FromBinaryString('10111')	-- 23
select chm.FromBinaryString('10011')	-- 19
select chm.FromBinaryString('10?11')	-- 19
select chm.FromBinaryString('10a11')	-- 19