Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

add ascii bytes 2

Status
Not open for further replies.

MerryMadDad

Programmer
Dec 11, 2001
47
GB
Hello all, can anyone help me to add a series of ascii numbers together ?

The data comes in two bytes 00 (two seperate bytes) and could be for example 23 the first time and 65 the next time. I want to subract 23 from 65 when the characters are ascii - how ?

any help much appreciated

Robert
 
The usual way to convert ASCII strings to integers is to call StrToInt or StrToIntDef.

I suggest you use StrToIntDef if there is any chance that the strings may not contain valid ASCII digits.

So to add FieldA to FieldB your code might look something like:
Code:
function AddFields ( const FieldA, FieldB: string ): integer;
const
  Invalid = 99999;
var
  a: integer;
  b: integer
begin
  a := StrToIntDef ( FieldA, Invalid );
  b := StrToIntDef ( FieldB, Invalid );
  if ( a <> Invalid ) and ( b <> Invalid ) then
    result := a + be
  else
    raise an error;
end;
There is a little &quot;gotcha&quot; in that StrToInt and StrToIntDef will also convert hexadecimal numbers. I had some invalid decimal data which consisted of 'X16' and StrToIntDef converted this to 22 (decimal) and did not give me an invalid number which was what I was expecting. So take care.

Of course, you should really implement a class called TASCIInumbers or something and define a whole series of methods to do arithmetic but I guess you might consider this overkill.

Andrew
 
Once you have ascii characters you can do something like this ( I haven't compiled this, but I think it's right. That's the danger of typing in this editor when you lazily depend upon the compiler to fix your mistakes).

Sadly, I have never dealt with data as bytes, so I may be overlooking an important detail (or 5 of them).

function AsciiCharToInt(AChar:Char):integer;
begin
if ((ord(AChar) >= 48) and (ord(AChar) <= 57)) then
AsciiInteger = ord(AChar);
end;

You can add the characters together as strings like this

i := StrToInt(IntToStr(AsciiCharToInt(Char1)) + IntToStr(AsciiCharToInt(Char2)));

or like this

i := (AsciiCharToInt(Char1)*10) + AsciiCharToInt(Char2)

Brian &quot;The difference between practice and theory is that in theory, there is no difference between practice and theory&quot; - Somebody's tag line I stole
 
I didn't know about that StrToIntDef function. I only wish I'd known sooner. Star for you. &quot;The difference between practice and theory is that in theory, there is no difference between practice and theory&quot; - Somebody's tag line I stole
 
Thanks to Andrew and Brian for their posts, but I still have a problem with this. I thought of strtoint and that stuff, but the problem I have is that each character or number is a seperate byte, so what do I do to detect a &quot;carry&quot; as in 9 + 9 would give 18 but the 8 should be in the &quot;low&quot; byte and the &quot;1&quot; added to the contents of the next byte. I guess subtraction would be similar :)

Regards Robert
 
So, strip off the extra digit and do the carry yourself, the same as if you were doing it pencil and paper.
 
It is not clear to me what you are asking for. On one hand you refer to &quot;add ascii bytes&quot; and in the request you refer to &quot;subtract 23 from 65&quot;

If you mean that you are getting a &quot;number&quot; like 65 as two bytes (strings) &quot;6&quot; and &quot;5&quot; and another &quot;number&quot; like 18 as two bytes (strings) &quot;1&quot; and &quot;8&quot; then this may be the function you are looking for. If not, please explain more carefully what it is that you really need.

Code:
function AddBytes( var B1High, B1Low:string; B2High, B2Low:string ):boolean;
var
  B1,B2:integer;
begin
  Result := False;
  B1 := StrToIntDef(B1High+B1Low,-1);
  B2 := StrToIntDef(B2High+B2Low,-1);
  if B1 >= 0 then
    if B2 >= 0 then
      begin
        B1 := B1 + B2;
        if B1 < 99 then
          begin
            B1High := Copy(IntToStr(B1),1,1);
            B1Low  := Copy(IntToStr(B1),2,1);
            Result := True;
          end;
      end;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  B1H,B1L:string;
begin
  B1H := '1';
  B1L := '8';
  if AddBytes( B1H, B1L, '6', '5' ) then
    ShowMessage('Answer=' + B1H + B1L )
  else
    ShowMessage('Error');
end;
 
Thank you Zathras, the first procedure seems to be what I am looking for the numbers or characters come in as seperate bytesand it is these that I want to add or subtract sorry for the confusion - I'm old :)

Loren, I don't know how to &quot;strip off&quot; the extra digit, I'll go away now and try Zathras suggestin

Thanks to all

Robert
 
Thank you Zathras, the first procedure seems to be what I am looking for the numbers or characters come in as seperate bytesand it is these that I want to add or subtract sorry for the confusion - I'm old :)

Loren, I don't know how to &quot;strip off&quot; the extra digit, I'll go away now and try Zathras suggestion

Thanks to all

Robert
 
Thank you.

If you use the code, please correct the line

if B1 < 99 then

which should have been

if B1 <= 99 then

(I'm old, too. [glasses])
 
Hello Zathras, your suggestion worked fine thank you, I modified it to cater for more than two bytes and to cope with a carry in the case where the answer is <99 but now could you help me do the same but for subtraction ?

much appreciated :)

Robert - no good at maths :(
 
You don't give one a lot to work with, but here goes:

Directions for subtraction:

Use the &quot;-&quot; symbol in place of the &quot;+&quot; symbol.
 
Thank you Zathras :)
but what happens when the low byte is larger than the High byte during the use of the &quot;-&quot; sign ?

I mean that I am getting a &quot;number&quot; like 18 as two bytes (strings) &quot;1&quot; and &quot;8&quot; and another &quot;number&quot; like 65 as two bytes (strings) &quot;6&quot; and &quot;5&quot; and I want to subtract these two 18 - 65 could you help out again please ? :)

Thanks

Robert
 
First you asked for a routine to handle &quot;two bytes&quot; but then you said you &quot;modified it to cater for more than two bytes.&quot; It is still not clear to me what you really want.

Here are functions to handle up to four bytes, but without really knowing how the data is coming to you I don't know whether this is what you really want. For example, when set up for 4 bytes, and one of the numbers is &quot;65&quot; is the first byte &quot;6&quot; and the second &quot;5&quot; and the third and fourth blank, or is the first one &quot;0&quot;, the second one &quot;0&quot;, the third one &quot;6&quot; and the fourth one &quot;5&quot;? Or is there some other configuration that you have in mind? Are you trying to set up a high-precision math routine that could take more than 255 digits? I can't help you any more without specific requirements.

Code:
{Service function called by AddBytes and SubBytes}
function AddOrSubBytes( var Operand1:string; Operand2:string;
             var Negative:boolean; Subtract:boolean=False ):boolean;
var
  Op1,Op2:integer;
begin
  Op1 := StrToIntDef(Operand1,-1);
  Op2 := StrToIntDef(Operand2,-1);
  if (Op1 >= 0) and (Op2 >= 0) then
    begin
      if Subtract then
        Op1 := Op1 - Op2
      else
        Op1 := Op1 + Op2;
      if Op1 < 0 then
        begin
          Negative := True;
          Op1 := 0 - Op1;
        end;
      Operand1 := IntToStr(Op1);
      if Length(Operand1) < Length(Operand2) then
        Operand1 := StringOfChar(' ',Length(Operand2)-Length(Operand1)) + Operand1;
      Result := True;
    end
  else
    Result := False;
end;

{Add two &quot;numbers&quot; together (formatted as strings)}
function AddBytes( var Operand1:string; Operand2:string ):boolean;
var
  Negative:boolean;
begin
  Result := AddOrSubBytes( Operand1, Operand2, Negative);
end;

{Subtract two &quot;numbers&quot; (formatted as strings)}
function SubBytes( var Operand1:string; Operand2:string; var Negative:boolean ):boolean;
begin
  Result := AddOrSubBytes( Operand1, Operand2, Negative, True);
end;

{Demo use of AddBytes function}
procedure DemoAddBytes( Byte1A,Byte2A,Byte3A,Byte4A,
                        Byte1B,Byte2B,Byte3B,Byte4B:string);
var
  X1,X2:string;
begin
  X1 := Byte1A + Byte2A + Byte3A + Byte4A;
  X2 := Byte1B + Byte2B + Byte3B + Byte4B;
  if AddBytes( X1, X2 ) then
    ShowMessage('Answer=' + X1 )
  else
    ShowMessage('Error');
end;

{Demo use of SubBytes function}
procedure DemoSubBytes( Byte1A,Byte2A,Byte3A,Byte4A,
                        Byte1B,Byte2B,Byte3B,Byte4B:string);
var
  X1,X2:string;
  s:string;
  Neg:boolean;
begin
  X1 := Byte1A + Byte2A + Byte3A + Byte4A;
  X2 := Byte1B + Byte2B + Byte3B + Byte4B;
  if SubBytes( X1, X2, Neg ) then
    begin
      if Neg then s := 'minus ' else s := 'plus ';
      ShowMessage('Answer=' + s + X1 )
    end
  else
    ShowMessage('Error');
end;

{Get text from edit boxes and split into 8 bytes to demo AddBytes}
procedure TForm1.Button3Click(Sender: TObject);
var
  Text1,Text2:string;
  Byte1A,Byte2A,Byte3A,Byte4A:string;
  Byte1B,Byte2B,Byte3B,Byte4B:string;
begin
  Text1 := Copy('0000' + Edit3.Text,Length(Edit3.Text)+1,4);
  Text2 := Copy('0000' + Edit4.Text,Length(Edit4.Text)+1,4);
  Byte1A := Copy(Text1,1,1);
  Byte2A := Copy(Text1,2,1);
  Byte3A := Copy(Text1,3,1);
  Byte4A := Copy(Text1,4,1);
  Byte1B := Copy(Text2,1,1);
  Byte2B := Copy(Text2,2,1);
  Byte3B := Copy(Text2,3,1);
  Byte4B := Copy(Text2,4,1);
  DemoAddBytes( Byte1A,Byte2A,Byte3A,Byte4A,
                        Byte1B,Byte2B,Byte3B,Byte4B);
end;

{Get text from edit boxes and split into 8 bytes to demo SubBytes}
procedure TForm1.Button4Click(Sender: TObject);
var
  Text1,Text2:string;
  Byte1A,Byte2A,Byte3A,Byte4A:string;
  Byte1B,Byte2B,Byte3B,Byte4B:string;
begin
  Text1 := Copy('0000' + Edit3.Text,Length(Edit3.Text)+1,4);
  Text2 := Copy('0000' + Edit4.Text,Length(Edit4.Text)+1,4);
  Byte1A := Copy(Text1,1,1);
  Byte2A := Copy(Text1,2,1);
  Byte3A := Copy(Text1,3,1);
  Byte4A := Copy(Text1,4,1);
  Byte1B := Copy(Text2,1,1);
  Byte2B := Copy(Text2,2,1);
  Byte3B := Copy(Text2,3,1);
  Byte4B := Copy(Text2,4,1);
  DemoSubBytes( Byte1A,Byte2A,Byte3A,Byte4A,
                        Byte1B,Byte2B,Byte3B,Byte4B);
end;
 
Hi Zathras, Thank you very much for the help, you are very kind. What I really wanted was to add or subtract a six byte number where the bytes are presented as ascii characters, perhaps I should have said that at the start, but I thought if I got the basics, I could take it from there. You have helped a great deal and now the case is closed for me :)

Sorry for any confussion again, put it down to one of the following:

1 I hadn't had my warm glass of milk
2 It was the cat - it distracted me
3 The bairn was screaming his heed off
4 I was sober :)
5 old age ?

You choose !

Thanks again and best regards

 
If you have a screaming bairn, you cant be that old?
Steve :)
 
Final comment on this forum as the following has not a lot to do with Delphi Pascal or any other prog. language.
RE screaming bairn if anyone is interested in finding out more contact me on alnet@lineone.net

(Old) Robert :)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top