There is a string "4169BB8C". How to deploy it in reverse order of 2 characters to get "8CBB6941"?

var i:integer; str,s:string; begin str:='4169BB8C'; for i:=(length(str) div 2) downto 1 do begin s:= s+Copy(str, i+1, 2); end; print(str); print(s); end. 

Something is not very successful.

  • If you answer directly and simply, then through the cycle. But is it really possible for specific? - Sonic Myst
  • The length of the string is known. Cycle through the characters of the string from its end, and copy every two characters into the buffer. Then from the buffer we form the resulting string. That does not work? - Dima
  • Is this an arbitrary string, or a hexadecimal notation of something? a pair of two characters - bytes. 4 pairs - 4 bytes, or double word. do you still need to invert the string, or output the bytes of the integer in the reverse order? - teran

2 answers 2

Walk - so walk:

 var s: AnsiString; function BSwap(d: Dword): Dword; asm bswap eax end; begin s:= '4169BB8C'; Caption := BSwap(StrToInt('$'+s)).ToHexString; 

With loop and new line:

  ns := ''; for i:= length(s) div 2 downto 1 do ns:= ns + Copy(s, 2 * i - 1, 2); Caption := ns; 
  • one
    Well, I can)) I don’t understand the assembler, so I’d do it in the old manner with the for i..downto..do . But your option looks more cheerful! - Dima
  • The main thing is that the line really was a hex no more than 8 characters :) - teran
  • @Dima Yes, of course, the learning task must be solved in a cycle. The author cited a specific line of length 8, containing only hex-digits. - MBo
  • The question is not complete. If a 4-byte value is meant in HEX, then the answer is quite correct. - Max.
  • one
    in order to reduce the number of asm constructions, you can do the function swap(d: dword):dword; asm bswap eax; end; function swap(d: dword):dword; asm bswap eax; end; - teran
 var i: integer; str,s: string; begin str:='4169BB8C'; for i:=length(str) downto 1 do begin i:=i-1; s:= s+Copy(str, i, 2); end; print(str); print(s); end. 
  • 2
    Error in the code: operations on the counter in the loop body cannot be performed. The compiler will not allow. - Dima