Reputation: 1
I have: A string with hexadecimal values every 4 positions
00F701C101C900EC01E001D2
I need:
Separate these values from 4 in 4 positions and convert to decimal numbers in this way:
247, 449, 457, 480, 466
My column can have up to 1200 hexadecimal positions
Can you help me?
Tks!!!
Upvotes: 0
Views: 2988
Reputation: 27498
It would be faster to iterate through positions in the hexstring, rather than copying the remainder of the string into itself after getting the hexdec.
Example:
data _null_ ;
length s $1200 ;
call streaminit(20240628);
do i = 1 to 1e5 ;
do j = 0 to 299 ;
h = put(rand('integer',65535),hex4.);
substr(s,1+j*4,4) = h ;
end ;
s2 = s;
t = datetime() ;
/* Slow way because s=substr(s,5) */
do while(s ne '') ;
hex4 = substr(s, 1, 4);
hexdec = input(hex4, hex4.);
s = substr(s, 5);
end ;
u = datetime() ;
/* Faster way, iterate position (j) */
do j = 1 to length(s2) ;
hex4 = substr(s2,j,4);
hexdec = input(hex4, hex4.);
j + 3 ;
end ;
v = datetime() ;
e1 + (u-t) ;
e2 + (v-u) ;
end ;
put e1=/e2= ;
run ;
Upvotes: 0
Reputation: 67291
Sorry, I was to fast. This is SQL-Server syntax, probably not working for you, but you might get an idea...
Try it like this:
DECLARE @YourString VARCHAR(100)='00F701C101C900EC01E001D2';
WITH Separated AS
(
SELECT CAST(LEFT(@YourString,4) AS VARCHAR(MAX)) AS SourceString
,CAST(SUBSTRING(@YourString,5,10000) AS VARCHAR(MAX)) AS RestString
UNION ALL
SELECT LEFT(RestString,4)
,SUBSTRING(RestString,5,10000)
FROM Separated
WHERE LEN(RestString)>=4
)
SELECT *
,CAST(sys.fn_cdc_hexstrtobin(SourceString) AS VARBINARY(2))
,CAST(CAST(sys.fn_cdc_hexstrtobin(SourceString) AS VARBINARY(2)) AS INT)
FROM Separated
The result
+--------------+----------------------+--------------------+--------------------+
| SourceString | RestString | (Kein Spaltenname) | (Kein Spaltenname) |
+--------------+----------------------+--------------------+--------------------+
| 00F7 | 01C101C900EC01E001D2 | 0x00F7 | 247 |
+--------------+----------------------+--------------------+--------------------+
| 01C1 | 01C900EC01E001D2 | 0x01C1 | 449 |
+--------------+----------------------+--------------------+--------------------+
| 01C9 | 00EC01E001D2 | 0x01C9 | 457 |
+--------------+----------------------+--------------------+--------------------+
| 00EC | 01E001D2 | 0x00EC | 236 |
+--------------+----------------------+--------------------+--------------------+
| 01E0 | 01D2 | 0x01E0 | 480 |
+--------------+----------------------+--------------------+--------------------+
| 01D2 | | 0x01D2 | 466 |
+--------------+----------------------+--------------------+--------------------+
Upvotes: 0
Reputation: 1319
This works:
data out;
hex = "00F701C101C900EC01E001D2";
do while(hex ne "");
valHex = substr(hex, 1, 4);
hex = substr(hex, 5);
valDec = input(valHex, hex4.);
output;
end;
run;
but you'll want to add more error checking etc for your real solution.
Upvotes: 1