Posts Tagged ‘string



28
Mar
09

[VB.Net] Binary To String Conversion

    Public Function BinaryToString(ByVal Binary As String) As String
        Dim Characters As String = System.Text.RegularExpressions.Regex.Replace(Binary, "[^01]", "")
        Dim ByteArray((Characters.Length / 8 ) - 1) As Byte
        For Index As Integer = 0 To ByteArray.Length - 1
            ByteArray(Index) = Convert.ToByte(Characters.Substring(Index * 8, 8), 2)
        Next
        Return System.Text.ASCIIEncoding.ASCII.GetString(ByteArray)
    End Function

Usage:

Debug.WriteLine(BinaryToString("01110011 01101001 01101101 00110000 01101110"))

Would output:

sim0n

Debug.WriteLine(BinaryToString("01110011,01101001,01101101,00110000,01101110,"))

Would output:

sim0n

28
Mar
09

[VB.Net] String To Binary Conversion

    Public Function StringToBinary(ByVal Text As String, Optional ByVal Separator As String = " ") As String
        Dim oReturn As New System.Text.StringBuilder
        For Each Character As Byte In System.Text.ASCIIEncoding.ASCII.GetBytes(Text)
            oReturn.Append(Convert.ToString(Character, 2).PadLeft(8, "0"))
            oReturn.Append(Separator)
        Next
        Return oReturn.ToString
    End Function

Usage:

Debug.WriteLine(StringToBinary("sim0n")

Would output:
01110011 01101001 01101101 00110000 01101110

Debug.WriteLine(StringToBinary("sim0n", ","))

Would output:
01110011,01101001,01101101,00110000,01101110,

28
Mar
09

[Javascript] Char Code to Unicode Fullwidth Latin

The below code is used for converting normal strings of characters to strings of Fullwidth Latin Unicode characters.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >
<html xmlns="http://www.w3.org/1999/xhtml" >
<head >
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" / >
<title > Untitled Document</title >
<script language="javascript" type="text/javascript" >
function code() {
	var ine = document.getElementById('in');
	var oute = document.getElementById('out');
	oute.value = ""
	for(i=0; i<ine.value.length; i++) {
		if(ine.value.charCodeAt(i)  > = 33 && ine.value.charCodeAt(i) <= 270) {
			oute.value += String.fromCharCode(ine.value.charCodeAt(i) + 65248);
		} else if(ine.value.charCodeAt(i) == 32) {
			oute.value += String.fromCharCode(12288);
		}
	}
}
</script >
</head > 

<body >
<form id="form1" name="form1" method="post" action="" >
	<textarea name="textarea" id="in" cols="70" rows="7" onkeyup="code()" > </textarea>   <br /> <br />
	<textarea name="textarea" id="out" cols="70" rows="7" > </textarea>
</form >
</body >
</html >

Usage:
The above code creates 2 text areas. Type into the top and the bottom box will output the Unicode equivalent, e.g.
https://sim0n.wordpress.com/
http://sim0n.wordpress.com/

28
Mar
09

[VB.Net] Hex to String Conversion

Function HexToString(ByVal hex As String) As String
    Dim text As New System.Text.StringBuilder(hex.Length \ 2)
    For i As Integer = 0 To hex.Length - 2 Step 2
        text.Append(Chr(Convert.ToByte(hex.Substring(i, 2), 16)))
    Next
    Return text.ToString
End Function

Usage:

Debug.WriteLine(HexToString("73696D306E"))

Would output:
sim0n

28
Mar
09

[VB.Net] String to Hex Conversion

Migrating old code snippits over to the new blog.

Function StringToHex(ByVal text As String) As String
    Dim hex As String
    For i As Integer = 0 To text.Length - 1
        hex &= Asc(text.Substring(i, 1)).ToString("x").ToUpper
    Next
    Return hex
End Function

Usage:

Debug.WriteLine(StringToHex("sim0n"))

Would Output:
73696D306E

27
Mar
09

[VBA-Word] Syntax Highlighting Generator

Right, so I got fed up of attempting to format code to put it onto wordpress, so, I’ve updated all my posts using a Word-VBA based highlighter.
I’ve not used VBA for anything much before, so the code is reasonably slow (few seconds) but It generates easy to paste code, with span tags for the highlighted areas.

Sub TextFormat()
    Dim strFont As String
    Dim strColour As String
    Dim intStart As Integer
    Dim i As Integer
    Dim intFontSize As String
    Dim html As String

    intStart = 0
    strFont = ThisDocument.words.First.Font.Name
    strColour = ThisDocument.words.First.Font.Color
    i = 0
    intFontSize = "11px"
    html = "<div style='border: #660000 5px solid;' > <pre style='background-color:#ffffff;padding:3px;line-height:15px;' > "

    Selection.Find.ClearFormatting()
    Selection.Find.Replacement.ClearFormatting()
    With Selection.Find
        .Text = "<"
        .Replacement.Text = "<"
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With
    Selection.Find.Execute(Replace:=wdReplaceAll)
    With Selection.Find
        .Text = " > "
        .Replacement.Text = " > "
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With
    Selection.Find.Execute(Replace:=wdReplaceAll)

    For Each wItem In ThisDocument.words
        If Not wItem.Font.Color = strColour Or Not wItem.Font.Name = strFont Then
            Selection.Start = intStart
            Selection.End = i
            Selection.Select()

            html = html & "<span style='color: " + getColour(strColour) + " !important; font-family: " + strFont + " !important;font-size:" + intFontSize + " !important;' > " & Selection.Text & "</span > "

            strFont = wItem.Font.Name
            strColour = wItem.Font.Color

            intStart = i
        End If
        i = i + Len(wItem)
    Next

    Selection.Start = intStart
    Selection.End = i
    Selection.Select()

    html = html & "<span style='color: " + getColour(strColour) + " !important; font-family: " + strFont + " !important;font-size:" + intFontSize + " !important;' > " & Selection.Text & "</span > " + vbNewLine + "</pre > </div > "

    Selection.Text = html

    Selection.Copy()
    ThisDocument.Undo()

    MsgBox("Done")
End Sub

Function getColour(ByVal col As String) As String
    If col = -16777216 Or col = wdColorBlack Or col = 9999999 Then
        getColour = "#000000"
    ElseIf col = 16711680 Or col = wdColorBlue Then
        getColour = "#1014e7"
    ElseIf col = 1381795 Or col = wdColorBrown Then
        getColour = "#850404"
    ElseIf col = 32768 Or col = wdColorBrown Then
        getColour = "#067c0e"
    End If
End Function

(Speed-wise, this took around 5 seconds to generate)
You can add your own colours to the getColour function. This is used when parsing the text in the document. This program does NOT actually create the highlighting, but checks fonts and colours, and then creats the html code from the document.

The CSS is all easy to change, the div/pre is the border design and you can change the spans as they are added to the html.

27
Mar
09

[VB.Net] RandomString Generator II

An updated version of my random string generator.
This version is more versatile than the last, allowing for more flexibility in the output.

'''
''' A function to generate random strings
'''
''' The length of the returned string.
''' Define a custom set of characters that are possible to be chosen
''' Determines if the string should contain Alphabetical Characters. Default = True
''' Determines if the string should contain Numerical Characters. Default = True
''' Determines if the string should contain Symbols. Default = False
''' Determines if the string should contain Upper Case characters
''' Determines if the string should contain Lower Case characters
''' A random string of the desired length.
''' http://simon.ctranter.co.uk
Private Function RandomString(ByVal StringLength As Integer, Optional ByVal CustomCharacters As String = "", Optional ByVal Letters As Boolean = True, Optional ByVal Numbers As Boolean = True, Optional ByVal Symbols As Boolean = False, Optional ByVal UpperCase As Boolean = True, Optional ByVal LowerCase As Boolean = True) As String
    Dim randomG As New Random
    Dim randomN As Integer
    Const pwChars As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    Const pwNumbers As String = "0123456789"
    Const pwSymbols As String = "`¬!""£$%^&*()_)+-=[]{};':@#~/?.>,<|"""
    Dim str As String = ""
    While str.Length < StringLength
        Dim pwcharList As String = ""
        If Letters = True Then pwcharList &= pwChars
        If Numbers = True Then pwcharList &= pwNumbers
        If Symbols = True Then pwcharList &= pwSymbols
        pwcharList &= CustomCharacters
        randomN = randomG.Next(0, pwcharList.Length)
        If UpperCase = True And LowerCase = True Then
            Dim randomN2 = randomG.Next(0, 2)
            If randomN2 = 0 Then
                str &= Char.ToUpper(pwcharList(randomN), System.Globalization.CultureInfo.CurrentCulture)
            Else
                str &= Char.ToLower(pwcharList(randomN), System.Globalization.CultureInfo.CurrentCulture)
            End If
        ElseIf UpperCase = True Then
            str &= Char.ToUpper(pwcharList(randomN), System.Globalization.CultureInfo.CurrentCulture)
        ElseIf LowerCase = True Then
            str &= Char.ToLower(pwcharList(randomN), System.Globalization.CultureInfo.CurrentCulture)
        Else
            str &= pwcharList(randomN)
        End If
    End While
    Return str
End Function

As you can see, this version is slightly more complicated than the last, but as stated, it also allows for far more flexibility in the output strings.
Ill go over the function slightly:

Private Function RandomString( _
ByVal StringLength As Integer, _
    Optional ByVal CustomCharacters As String = "", _
    Optional ByVal Letters As Boolean = True, _
    Optional ByVal Numbers As Boolean = True, _
    Optional ByVal Symbols As Boolean = False, _
    Optional ByVal UpperCase As Boolean = True, _
    Optional ByVal LowerCase As Boolean = True) _
As String

The key thing to note about this version, is the introduction of the CustomCharacters paramater. This allows you to make random strings, but using your own predefined arrays of characters.

For example, if i was to use this:

Debug.WriteLine(RandomString(20, "simon.ctranter.co.uk", False, False, False))

It would output something like this:
t.scCKcrn.CN.o..A.Ms
As to make the string, it only uses characters from the CustomCharacters parameter.

So, what use is this?
It allows you to make “random strings” that, are more recognisable, for example, using:

Debug.WriteLine(RandomString(40, "simonsimonsimonsimonsimonsimon", False, False, False, True, True))

You would get:
ISnoNnSsNinSioommOSNNSsMoSiomsOoSSIiMsIO

Which could then be made more complex by allowing symbols, but also increasing the length of the CustomCharacters (So it is still more likley to pick on of the characters from ‘simon’):

Debug.WriteLine(RandomString(40, "simonsimonsimonsimonsimonsimonsimonsimonsimonsimonsimonsimon", False, False, True, True, True))

Would return:
.~&)>M|mS}SNIsn[iiNSoonOSSM”Nmi*O|_(S)i

27
Mar
09

[VB.Net] RandomString Generator

Some guy on MSN asked me to write a function to generate random strings for him, here is the slightly modified result:

'''
''' A function to generate random strings
'''
''' An integer value between 0 and 2.
''' 0 returns a random string of numbers and letters, 1 returns a random string of letters and 2 returns a random string of numbers.
''' Any other value will return a random string of numbers and letters.
''' A random string of the desired length.
''' The length of the returned string.
''' http://simon.ctranter.co.uk
Private Function RandomString(ByVal Mode As Integer, ByVal StringLength As Integer) As String
    Dim randomG As New Random
    Dim randomN As Integer
    Const pwChars As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    Const pwNumbers As String = "0123456789"
    Dim str As String = ""
    While str.Length < StringLength
        If Not Mode = 1 And Not Mode = 2 Then
            randomN = randomG.Next(0, 2)
            If randomN = 0 Then
                randomN = randomG.Next(0, 26)
                str &= pwChars(randomN)
            Else
                randomN = randomG.Next(0, 10)
                str &= pwNumbers(randomN)
            End If
        ElseIf Mode = 1 Then
            randomN = randomG.Next(0, 26)
            str &= pwChars(randomN)
        ElseIf Mode = 2 Then
            randomN = randomG.Next(0, 10)
            str &= pwNumbers(randomN)
        End If
    End While
    Return str
End Function

Usage:

Debug.Write(RandomString(0, 25))

Would output:
32ECXD20AK9T1825832MZBWYG