Shop OBEX P1 Docs P2 Docs Learn Events
MID$ in Spin? — Parallax Forums

MID$ in Spin?

MoskogMoskog Posts: 554
edited 2012-09-09 14:07 in Propeller 1
Can anyone help me with a MID$ function in spin?

Example: (Two strings: date and mm)
date = "09:10:12" (Known value)

mm = MID$ (date,4,2) .. that will return "10", how do I do that?


Then how would be the simplest way to convert the string mm into a decimal value?

Comments

  • Mike GreenMike Green Posts: 23,101
    edited 2012-09-09 09:37
    Strings are stored as byte arrays with a zero byte marking the end of the string. In your case, the strings are fixed length and a known format. You could just copy the appropriate bytes as follows:
    VAR  byte mm[ 3 ], date[ 9 ], theValue
    
    bytemove(@mm,@date+3,2)   ' copy the two bytes
    mm[2]~   ' set zero byte if necessary
    theValue := (mm[ 0 ] - "0")*10 + (mm[ 1 ] - "0")   ' convert to decimal value
    
  • Phil Pilgrim (PhiPi)Phil Pilgrim (PhiPi) Posts: 23,514
    edited 2012-09-09 09:52
    Mike beat me to it, but here's what I came up with:
    VAR
    
      byte hh[3], mm[3], ss[3]
      byte hour, minute, second  
    
    PUB start | time
    
      time := string("12:45:13")
    
      'Break string into pieces:
      
      midstr(@hh, time, 0, 2)
      midstr(@mm, time, 3, 2)
      midstr(@ss, time, 6, 2)
    
      'Or, more simply, do this to get actual values:
    
      hour := str2val(time)
      minute := str2val(time + 3)
      second := str2val(time + 6)
    
    PUB midstr(destaddr, srcaddr, first, len)
    
      'Copy part of a string to another string.
    
      bytemove(destaddr, srcaddr + first, len)
      byte[destaddr + len]~
    
    PUB str2val(straddr) | c
    
      'Accumulate a value from string as long as processing actual digits.
    
      repeat while (c := byte[straddr++]) => "0" and c =< "9"
        result := result * 10 + c - "0"
    

    The first method just breaks up the string without doing a conversion; the second, skips the breakup altogether and just does the conversion to numbers.

    -Phil
  • MoskogMoskog Posts: 554
    edited 2012-09-09 14:07
    Thank you so much, Mike and Phil for that quick respond!

    I really do appreciate you being so helpful when I'm stuck in difficulties!
Sign In or Register to comment.