Concatenate string to int - General - Algorand
Concatenate string to int
post by pagito on Jun 1, 2021
Hi all! I want to save value under the key “string_1”, where the string is a constant suffix and 1 comes from the counter. The following code:
byte "MyCounter"
app_global_get
int 1
+ // increment
store 0
byte "string_" // suffix
load 0
itob // convert to byte
concat
int 6
btoi
app_global_put
Writes data like this:
"string_\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001": {
"tt": 2,
"ui": 6
},
itob opcode converts it to big endian bytes, that’s why it saves like this. How can it be achieved to concatenate bytes and int with readable format?
post by Maugli on Jun 1, 2021
Hi. You can use setbyte:
cat inc.teal
#pragma version 3
//byte "MyCounter"
//app_global_get
//int 1
//+ // increment
//store 0
int 1234
int 1
+
store 0
byte "string_" // suffix
byte "0"
int 0
load 0
store 1
load 1
int 10
%
store 2
load 2
int 48
+
setbyte // last digit as str
store 3
byte "0"
int 0
load 1
load 2
-
int 10
/
store 1
load 1
int 10
%
store 2
load 2
int 48
+
setbyte
store 4
byte "0"
int 0
load 1
load 2
-
int 10
/
store 1
load 1
int 10
%
store 2
load 2
int 48
+
setbyte
store 5
byte "0"
int 0
load 1
load 2
-
int 10
/
store 1
load 1
int 10
%
store 2
load 2
int 48
+
setbyte
store 6
byte "0"
int 0
load 1
load 2
-
int 10
/
store 1
load 1
int 10
%
store 2
load 2
int 48
+
setbyte
store 7
byte "0"
int 0
load 1
load 2
-
int 10
/
store 1
load 1
int 10
%
store 2
load 2
int 48
+
setbyte
store 8
byte "0"
int 0
load 1
load 2
-
int 10
/
store 1
load 1
int 10
%
store 2
load 2
int 48
+
setbyte
store 9
byte "0"
int 0
load 1
load 2
-
int 10
/
store 1
load 1
int 10
%
store 2
load 2
int 48
+
setbyte
store 10
byte "0"
int 0
load 1
load 2
-
int 10
/
store 1
load 1
int 10
%
store 2
load 2
int 48
+
setbyte
store 11
byte "0"
int 0
load 1
load 2
-
int 10
/
store 1
load 1
int 10
%
store 2
load 2
int 48
+
setbyte
store 12
load 12
concat
load 11
concat
load 10
concat
load 9
concat
load 8
concat
load 7
concat
load 6
concat
load 5
concat
load 4
concat
load 3
concat
If you run it with tealdbg, there will be “string_0000001235” on the stack. Probably the same can be done much more efficiently, but I simply repeated a block of code, and then concatenated the ascii digits in reverse order.