Home > Software engineering >  Delphi byte array leading zeroes (?empty? spaces in array)
Delphi byte array leading zeroes (?empty? spaces in array)

Time:10-07

I'm trying to add 00 for each byte array element that is missing, to explain it better, if lenght of an array is 20 and the string fills only 9 spaces (reversed), I need the rest 11 spaces to be 00. An example will explain it better.

This is my code so far:

   var
      dateAndTimeOfIssue, taxPayerId: Tarray<Byte>;
      dateOfIssueMS, DOIReversed: int64;
   begin
      dateOfIssueMS := StrToInt64(MilliSecondsBetween(f.InvoiceRequest.dateAndTimeOfIssue, 
                       UnixDateDelta).ToString);
      ReverseBytes(@(dateofIssueMS), @(DOIReversed), SizeOf(dateofIssueMS));
      setLength(dateAndTimeOfIssue, 8);
      Move(DOIReversed, dateAndTimeOfIssue[0], SizeOf(DOIReversed));
      // result of this byte array casted into hex string is  
         '0000313B23048B31' // which is correct

      setlength(taxPayerId, 20);
      taxPayerId := TEncoding.UTF8.GetBytes(F.MyCompany.taxpayerId);
      // result of this byte array casted into hex string is
         '303231313331363832' // and I need it to be 
         '0000000000000000000000303231313331363832'

What I am actually trying to achieve is add multiple byte arrays into one final array that will be sent to SmartCard, these are just the 2 arrays here for example (I'm using hexadecimal strings only to represent what the bytes look like because I have a full example of how it should be). APDU Commands are weird, thanks in advance.

CodePudding user response:

The actual tax payer Id seems to be 9 characters: '021131682'. For a total length of 20 bytes you need 11 null bytes first in the ArrTaxPayerId array. So, with BufferSize=20, StrTaxPayerId='021131682' you can set the initial length of ArrTaxPayerId:

SetLength(ArrTaxPayerId, BufferSize - Length(StrTaxPayerId);

That will now hold 11 null bytes. Then you concatenate it with the bytes of the actual tax payer ID:

ArrTaxPayerId := ArrTaxPayerId   TEncoding.UTF8.GetBytes(StrTaxPayerId);

Then the final step is to convert the 20 byte ArrTaxPayerId to hex representation using BinToHex() which you already have the code for.

When I tried the above I got a result of 0000000000000000000000303231313331363832

  • Related