Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to OR 2 strings of 0,1

Tags:

sql-server

bit

I have 2 string that just contains 0 and 1. I want a result string that bitwise OR them charcter by character.

DECLARE @str1 nvarchar;
DECLARE @str2 nvarchar; 
SET @str1= '11001100';
SET @str2= '00100110';

-- I want result to be : 11101110

The size of string is variable. I can use a for loop and OR the characters one by one. but the number of strings is variable and the size of them may be more than 1 million... Is there any better way than FOR loop?

like image 841
mjyazdani Avatar asked Jan 01 '15 10:01

mjyazdani


People also ask

Do strings start at 0 or 1 Python?

String indexing in Python is zero-based: the first character in the string has index 0 , the next has index 1 , and so on. The index of the last character will be the length of the string minus one.

Do strings start at index 0?

The beginning character of a string corresponds to index 0 and the last character corresponds to the index (length of string)-1 . The length of a string is the number of characters it contains, including spaces, punctuation, and control characters.

What does :: 1 mean in Python?

If you leave slots empty, there's a default. [:] means: The whole thing. [::1] means: Start at the beginning, end when it ends, walk in steps of 1 (which is the default, so you don't even need to write it). [::-1] means: Start at the end (the minus does that for you), end when nothing's left and walk backwards by 1.


1 Answers

Ideally you would be encoding this as binary.

11001100 is a single byte 0xCC.

Storing as varchar means it takes 8 bytes and declared as nvarchar it takes 16 bytes.

You could then also use CLR and bitwise operators.

Answering the question you asked though using a CLR function would likely still be by far the best performing way.

using System;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;

public partial class UserDefinedFunctions
{
    [SqlFunction]
    public static SqlString StringOr(SqlChars a, SqlChars b)
    {
        if (a.Length != b.Length)
        {
            throw new Exception("Strings should be the same length.");
        }

        char[] c = new char[a.Length];

        for(int i =0; i < a.Length; i++)
        {
            c[i] = (a[i] == '0' && b[i] == '0' ? '0' : '1');
        }

        return (SqlString)(new SqlChars(c));        
    }
}

enter image description here

like image 155
Martin Smith Avatar answered Nov 15 '22 08:11

Martin Smith