Author Topic: ( Challenge ) StringToBinary  (Read 10587 times)

0 Members and 1 Guest are viewing this topic.

gile

  • Gator
  • Posts: 2507
  • Marseille, France
Re: ( Challenge ) StringToBinary
« Reply #30 on: March 21, 2009, 10:21:02 AM »
Quote
However, you're returning a string, in C# you should return a string array.
It does return a string array.

Vovka's one translation

Code: [Select]
static string[] StringToBinary(string str)
{
    Byte[] bytes = Encoding.ASCII.GetBytes(str);
    string[] result = new string[bytes.Length];
    for (int i = 0; i < bytes.Length; i++)
    {
        result[i] = DecToBin(bytes[i], 8);
    }
    return result;
}

static string DecToBin(int dec, int len)
{
    return len < 2 ? (dec % 2).ToString() : DecToBin(dec / 2, len - 1) + (dec % 2).ToString();
}
Speaking English as a French Frog

MP

  • Seagull
  • Posts: 17750
  • Have thousands of dwgs to process? Contact me.
Re: ( Challenge ) StringToBinary
« Reply #31 on: March 21, 2009, 10:23:21 AM »
OOPS. Sorry Gile, I shouldn't post before my first coffee; forgive me.
Engineering Technologist • CAD Automation Practitioner
Automation ▸ Design ▸ Drafting ▸ Document Control ▸ Client
cadanalyst@gmail.comhttp://cadanalyst.slack.comhttp://linkedin.com/in/cadanalyst

MP

  • Seagull
  • Posts: 17750
  • Have thousands of dwgs to process? Contact me.
Re: ( Challenge ) StringToBinary
« Reply #32 on: March 21, 2009, 10:35:34 AM »
Code: [Select]
static string[] StringToBinary(string str)
{
    Byte[] bytes = Encoding.ASCII.GetBytes(str);
    string[] result = new string[bytes.Length];
    for (int i = 0; i < bytes.Length; i++)
    {
        result[i] = DecToBin(bytes[i], 8);
    }
    return result;
}

static string DecToBin(int dec, int len)
{
    return len < 2 ? (dec % 2).ToString() : DecToBin(dec / 2, len - 1) + (dec % 2).ToString();
}

Translated to Python:

Code: [Select]
def stringToBinary(s):
    bytes=list(map(ord,s)); result=[]
    for i in range(0,len(bytes)):
        result+=[decToBin(bytes[i])]
    return result

def decToBin(dec,bits=8):
    return str(dec%2) if bits < 2 else decToBin(dec//2,bits-1) + str(dec%2)

Hope you don't mind, I need the practice and this is a fun way to achieve it. :)
Engineering Technologist • CAD Automation Practitioner
Automation ▸ Design ▸ Drafting ▸ Document Control ▸ Client
cadanalyst@gmail.comhttp://cadanalyst.slack.comhttp://linkedin.com/in/cadanalyst

gile

  • Gator
  • Posts: 2507
  • Marseille, France
Re: ( Challenge ) StringToBinary
« Reply #33 on: March 21, 2009, 10:45:42 AM »
Quote
I need the practice and this is a fun way to achieve it.

So do I.
Speaking English as a French Frog

gile

  • Gator
  • Posts: 2507
  • Marseille, France
Re: ( Challenge ) StringToBinary
« Reply #34 on: March 21, 2009, 12:11:05 PM »
Another way

LISP
Code: [Select]
(defun StringToBinary (str / d2b left0)
 
  (defun d2b (n i / m)
    (if (zerop (setq m (lsh n i)))
      0
      (if (zerop (rem m 2))
(d2b n (1- i))
(+ (expt 10 (- i)) (d2b n (1- i)))
      )
    )
  )
 
  (defun left0 (s l)
    (while (< (strlen s) l) (setq s (strcat "0" s)))
  )
 
  (mapcar '(lambda (x) (left0 (itoa (d2b x 0)) 8))
  (vl-string->list str)
  )
)

C#

Code: [Select]
static string[] StringToBinary(string str)
{
    Byte[] bytes = Encoding.ASCII.GetBytes(str);
    string[] result = new string[bytes.Length];
    for (int i = 0; i < bytes.Length; i++)
        result[i] = String.Format("{0:00000000}", dec2bin(bytes[i], 0));
    return result;
}

static int dec2bin(int n, int i)
{
    int s = n >> i;
    return s == 0 ? 0 : s % 2 == 0 ? dec2bin(n, i + 1) : (int)Math.Pow(10, i) + dec2bin(n, i + 1);
}
« Last Edit: March 21, 2009, 12:14:22 PM by gile »
Speaking English as a French Frog

MP

  • Seagull
  • Posts: 17750
  • Have thousands of dwgs to process? Contact me.
Re: ( Challenge ) StringToBinary
« Reply #35 on: March 21, 2009, 12:54:08 PM »
Code: [Select]
static string[] StringToBinary(string str)
{
    Byte[] bytes = Encoding.ASCII.GetBytes(str);
    string[] result = new string[bytes.Length];
    for (int i = 0; i < bytes.Length; i++)
        result[i] = String.Format("{0:00000000}", dec2bin(bytes[i], 0));
    return result;
}

static int dec2bin(int n, int i)
{
    int s = n >> i;
    return s == 0 ? 0 : s % 2 == 0 ? dec2bin(n, i + 1) : (int)Math.Pow(10, i) + dec2bin(n, i + 1);
}

Converted to Python:

Code: [Select]
def stringToBinary(s):
    bytes=list(map(ord,s)); result=[]
    for i in range(0,len(bytes)):
        result+=[bin(bytes[i])[2:].zfill(8)]
    return result

Revising one of my earlier submissions:

Code: [Select]
def stringToBinary(s):
    return list(map(lambda a: bin(ord(a))[2:].zfill(8),s))

:D
Engineering Technologist • CAD Automation Practitioner
Automation ▸ Design ▸ Drafting ▸ Document Control ▸ Client
cadanalyst@gmail.comhttp://cadanalyst.slack.comhttp://linkedin.com/in/cadanalyst

MP

  • Seagull
  • Posts: 17750
  • Have thousands of dwgs to process? Contact me.
Re: ( Challenge ) StringToBinary
« Reply #36 on: March 21, 2009, 01:13:51 PM »
Code: [Select]
def stringToBinary(s):
    bytes=list(map(ord,s)); result=[]
    for i in range(0,len(bytes)):
        result+=[bin(bytes[i])[2:].zfill(8)]
    return result

If one preferred the use of a pre-allocated list rather than appending the result:

Code: [Select]
def stringToBinary(s):
    bytes=list(map(ord,s)); result=['']*len(bytes)
    for i in range(0,len(bytes)):
        result[i]=bin(bytes[i])[2:].zfill(8)
    return result

Such a cool language. :)
Engineering Technologist • CAD Automation Practitioner
Automation ▸ Design ▸ Drafting ▸ Document Control ▸ Client
cadanalyst@gmail.comhttp://cadanalyst.slack.comhttp://linkedin.com/in/cadanalyst

MP

  • Seagull
  • Posts: 17750
  • Have thousands of dwgs to process? Contact me.
Re: ( Challenge ) StringToBinary
« Reply #37 on: March 21, 2009, 04:03:43 PM »
Turns out I could have employed the range function more efficiently:

Original:
Code: [Select]
def stringToBinary(s):
    bytes=list(map(ord,s)); result=['']*len(bytes)
    for i in range([color=red]0,[/color]len(bytes)):
        result[i]=bin(bytes[i])[2:].zfill(8)
    return result

Improved:
Code: [Select]
def stringToBinary(s):
    bytes=list(map(ord,s)); result=['']*len(bytes)
    for i in range(len(bytes)):
        result[i]=bin(bytes[i])[2:].zfill(8)
    return result

Subtitle: If the intent is to iterate over the indexes of an indexed iterable object, there's no need to specify the lower boundary (0) because the range function will supply 0 in the absence of a specific lower bound; cool. :lightbulb:

/carry on
Engineering Technologist • CAD Automation Practitioner
Automation ▸ Design ▸ Drafting ▸ Document Control ▸ Client
cadanalyst@gmail.comhttp://cadanalyst.slack.comhttp://linkedin.com/in/cadanalyst

adalea03

  • Guest
Re: ( Challenge ) StringToBinary
« Reply #38 on: March 22, 2009, 09:52:02 AM »
While I admire the beauty of the posted examples, I'm puzzled.
So, from a "pea brained" person's perspective...Why?
What is the intended purpose?
There is occupational incentive for me to continue to learn Lisp/VL,
so can I assume that this challenge would likely be carried to the level
of implementing the code for a purpose.
And if it is "just  for the fun of it", that's okay too.
You folks amaze me.
Tony

MP

  • Seagull
  • Posts: 17750
  • Have thousands of dwgs to process? Contact me.
Re: ( Challenge ) StringToBinary
« Reply #39 on: March 22, 2009, 10:02:22 AM »
Why? What is the intended purpose?

Not sure I understand Tony ... why bother writing binary functions? (was just for academic fun) or why am I trying to use/learn Python? (I've been wanting to learn it for years for general programming, especially web based stuff).

There is occupational incentive for me to continue to learn Lisp/VL, so can I assume that this challenge would likely be carried to the level
of implementing the code for a purpose.

In my own use I've only ever penned binary functions to illuminate what happens at the binary level to those just beginning to program.

And if it is "just  for the fun of it", that's okay too.

And there's this. :)

You folks amaze me.Tony

The skills of our friends from around the world are impressive and I'm glad they've decided to hang their hats here and share their expertise. We all win.

:)
« Last Edit: March 22, 2009, 10:26:20 AM by MP »
Engineering Technologist • CAD Automation Practitioner
Automation ▸ Design ▸ Drafting ▸ Document Control ▸ Client
cadanalyst@gmail.comhttp://cadanalyst.slack.comhttp://linkedin.com/in/cadanalyst

adalea03

  • Guest
Re: ( Challenge ) StringToBinary
« Reply #40 on: March 22, 2009, 11:21:19 AM »
Quote
The skills of our friends from around the world are impressive and I'm glad they've decided to hang their hats here and share their expertise. We all win.


So very true (re:all winning ).
It is for that dose of commaraderie and the display of those "impressive skills" that I return when I can.
(to see, that is; I have none to disply, yet.)
I still wonder; Is Python a language that is effective for Acad?

Tony

hermanm

  • Guest
Re: ( Challenge ) StringToBinary
« Reply #41 on: April 05, 2009, 03:39:12 PM »
OK, old thread, but here is my entry:

Code: [Select]
;;using lambda function - no apparent speed advantage to named function call
(defun string->bin_strings (str / )
  (mapcar '(lambda (str / mask out)
            (setq out "" mask 128)
              (repeat 8
                (if (zerop (logand arg mask))
                  (setq out (strcat out "0"))
                  (setq out (strcat out "1"))
                )
              (setq mask (/ mask 2))

              )
            out
           )
   (vl-string->list str))
)

After I got past this garbage:

Code: [Select]
;;naive iterative version - 8 bits - a real dog
(defun byte->bin_string (arg / n out power2)
   (setq n 8 out "")
   (repeat 8
      (setq n (1- n)
            power2 (expt 2 n))
      (if (>= arg power2)
        (progn
          (setq out (strcat out "1")
                arg (- arg power2))
        )
        (setq out (strcat out "0"))
      )

   )
   out
)


I tried 3 ways of doing basically the same thing:

Code: [Select]
;;iterative - using logand from high bit - much faster than first one (no surprise)
(defun int->bin_string-l (arg / mask out)
   (setq out "" mask 128)
   (repeat 8
      (if (zerop (logand arg mask))
        (setq out (strcat out "0"))
        (setq out (strcat out "1"))
      )
      (setq mask (/ mask 2))

   )
   out
)

;;iterative - using logand from low bit - slightly slower than above!
(defun int->bin_string-r (arg / mask out)
   (setq out "" mask 1)
   (repeat 8
      (if (zerop (logand arg mask))
        (setq out (strcat "0" out))
        (setq out (strcat "1" out))
      )
      (setq mask (* mask 2))

   )
   out
)

;;iterative - using logand & lsh from low bit - slower than using multiply!
(defun int->bin_string-lsh (arg / mask out)
   (setq out "" mask 1)
   (repeat 8
      (if (zerop (logand arg mask))
        (setq out (strcat "0" out))
        (setq out (strcat "1" out))
      )
      (setq mask (lsh mask 1))

   )
   out
)


Test results using BenchRRB by Robt. Bell:
Note: -> results not 100% repeatable - I am not sophisticated enough to know why
So, I suggest running the same test multiple times (like, 5 or 6)
(This could be a whole 'nother topic)

Command: (bench '(int->bin_string-l int->bin_string-r int->bin_string-lsh)
(_> '(255) 1000)

INT->BIN_STRING-L
Elapsed: 15
Average: 0.0150

INT->BIN_STRING-R
Elapsed: 16
Average: 0.0160

INT->BIN_STRING-LSH
Elapsed: 32
Average: 0.0320

Test of posted complete functions:

;;;timing using BenchRRB <- not 100% consistent - must run multiple times
Command: (bench '(_strtobin eea-str2bin stringtobinary-tw stringtobinary-gile
('(_> string->bin_strings) '("ABCD") 1000)

_STRTOBIN - MP
Elapsed: 110
Average: 0.1100

EEA-STR2BIN
Elapsed: 79
Average: 0.0790

STRINGTOBINARY-TW
Elapsed: 78
Average: 0.0780

STRINGTOBINARY-GILE - 1st Post
Elapsed: 94
Average: 0.0940

STRING->BIN_STRINGS
Elapsed: 78
Average: 0.0780

@ MP:
I think (expt) is slowing yours down
Yes, I see that part of your intention was to compare language solutions, so probably you could write faster LISP if you intended to only do that. Now, I am determined to explore some .NET - it is time.:)
@ Gile:
I didn't test your subsequent LISP post
@ TW:
Your entry is far from "cheesy"
@ Vovka:
Sorry, I kept getting a "cannot reenter LISP" error when I tried to wrap your nice recursion, so I had to omit yours.
Please accept my apology for not being able to find my error.
@ Evgeny:
Impressive. Concise & fast.
You da man.:)

Comments:

I would naively expect (lsh) to beat * or /. However, the results I got here agree with my past experience, that (lsh) is not as fast as one might expect, given its definition. I conclude it is implemented in a way not very close to the hardware.



hermanm

  • Guest
Re: ( Challenge ) StringToBinary
« Reply #42 on: April 05, 2009, 03:51:01 PM »
Whoops:
Code: [Select]
;;using lambda function - no apparent speed advantage to named function call
(defun string->bin_strings (str / )
  (mapcar '(lambda (str / mask out)
            (setq out "" mask 128)
              (repeat 8
                (if (zerop (logand str mask))
                  (setq out (strcat out "0"))
                  (setq out (strcat out "1"))
                )
              (setq mask (/ mask 2))

              )
            out
           )
   (vl-string->list str))
)

Attached: Robert Bell's "Bench" program, which I used to test speed of posted functions.
Anyone is free to dissect that, or provide a better one.

It's Alive!

  • Retired
  • Needs a day job
  • Posts: 8696
  • AKA Daniel
Re: ( Challenge ) StringToBinary
« Reply #43 on: April 06, 2009, 01:59:15 AM »
mine

Code: [Select]
static int ads_stringtobinary(void)
  {
    TCHAR outbuff[33];
    TCHAR formatedBuff[33];
    const int padding = (sizeof(int)*8+1);
    struct resbuf *pArgs =acedGetArgs () ;
    struct resbuf *pHead = acutNewRb(RTSTR);
    struct resbuf *pTail = pHead;
   
    while(pArgs)
    {
      if(pArgs->restype == RTSTR)
      {
        pTail = pTail->rbnext = acutNewRb(RTLB);
        for(int i = 0 ;i < _tcsclen(pArgs->resval.rstring) ; i++)
        {
          pTail = pTail->rbnext = acutNewRb(RTSTR);
          _itot(pArgs->resval.rstring[i] , outbuff, 2);
          _stprintf_s(formatedBuff,sizeof(formatedBuff),_T("%08s"),outbuff);
          pTail->resval.rstring = _tcsdup(formatedBuff);
        }
        pTail = pTail->rbnext = acutNewRb(RTLE);
      }
      pArgs = pArgs->rbnext;
    }

    if(pHead->rbnext) { acedRetList (pHead->rbnext); };
    acutRelRb(pHead);
    return (RSRSLT) ;
  }

It's Alive!

  • Retired
  • Needs a day job
  • Posts: 8696
  • AKA Daniel
Re: ( Challenge ) StringToBinary
« Reply #44 on: April 06, 2009, 05:26:41 AM »
my C# version

Code: [Select]
[LispFunction("StrToBin")]
    public static ResultBuffer StrToBin(ResultBuffer args)
    {
      List<string> strings = new List<string>();
      ResultBuffer rb = new ResultBuffer();
      if (args != null)
      {
        foreach (TypedValue tv in args)
          if (tv.TypeCode == (int)LispDataType.Text)
            strings.Add((string)tv.Value);
         
        strings.ForEach(S =>  new List<byte>
          (Encoding.ASCII.GetBytes(S)).ForEach
            (B => rb.Add(new TypedValue((int)LispDataType.Text,(Convert.ToString(B, 2).PadLeft(8,'0'))))));
      }
      return rb;
    }