Union query

Coding and general discussion relating to the compiler

Moderators: David Barker, Jerry Messina

Post Reply
SHughes_Fusion
Posts: 219
Joined: Wed Sep 11, 2013 1:27 pm
Location: Chesterfield

Union query

Post by SHughes_Fusion » Thu Apr 24, 2014 2:38 pm

I'm working on a routine that takes a number of seconds and converts it to a string containing minutes and seconds.

I was wondering, how exactly do unions work and can I use them for this? For example, if I declare

Code: Select all

  structure PTime
    TStr as string(7) union
    Mins as string(4) union
    Secs as string(3)
  end structure
would this give me a 7 byte string where I can access the first 4 characters and the last 3 characters separately?

What I'm thinking is that I can do PTime.Mins = DecToStr(Time/60,3," ") to get minutes, then PTime.Secs = DecToStr(Time mod 60,2) which will give me seconds and terminate TStr with a null. Then I do PTime.TStr(3)=":" to replace the terminator I got from the minutes conversion.

That should give me a string MMM:SS? Or am I misunderstanding structures and unions? Is there a better or simpler way to do this?
(I understand I need to declare a variable as the structure, this is just an example)

User avatar
David Barker
Swordfish Developer
Posts: 1214
Joined: Tue Oct 03, 2006 7:01 pm
Location: Saltburn by the Sea, UK
Contact:

Re: Union query

Post by David Barker » Thu Apr 24, 2014 4:35 pm

To do what you want to do, you would need:

Code: Select all

  Structure PTime
    Mins As String(4)
    Secs As String(3)
    Str As String(7) Union
  End Structure

Post Reply