简体   繁体   中英

How do I convert HEXADECIMAL to DECIMAL in SAS?

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!!!

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.

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                |
+--------------+----------------------+--------------------+--------------------+

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM