Published on :
Macro SASHELP

Generating an MD5 hash expression

This code is also available in: Deutsch Español Français
This macro, mp_md5, constructs a character string that, when executed in a DATA step, calculates a composite MD5 hash for the specified variables. It is designed to be robust in the face of complex cases such as large floating-point numbers, special numeric missing values, and a large number of columns. The algorithm concatenates the MD5 hashes of each individual variable. The documentation indicates that it does not work in a PROC SQL and may cause errors if the option 'options dsoptions=nonote2err;' is active and non-special missing data exists.
Data Analysis

Type : SASHELP


The macro is designed to apply to any SAS table being processed in a DATA step. The example provided in the documentation uses the SASHELP.CLASS table, which is a standard internal SAS source. No external data is needed for the example.

1 Code Block
Macro
Explanation :
Defines the 'mp_md5' macro which takes as parameters a list of character variables (cvars) and numeric variables (nvars). The macro dynamically generates a series of SAS function calls. For each variable, it calculates an individual MD5 hash ('put(md5(...),$hex32.)'). For numeric variables, it applies a trick `ifn(missing(&var),&var,&var*1)` to preserve special missing values while correcting floating-point precision errors. All individual hashes are then concatenated (separated by '!!') and the final result is itself hashed by the MD5 function to produce a single hash key.
Copied!
1%macro mp_md5(cvars=,nvars=);
2%local i var sep;
3put(md5(
4 %DO i=1 %to %sysfunc(countw(&cvars));
5 %let var=%scan(&cvars,&i,%str( ));
6 &sep put(md5(trim(&var)),$hex32.)
7 %let sep=!!;
8 %END;
9 %DO i=1 %to %sysfunc(countw(&nvars));
10 %let var=%scan(&nvars,&i,%str( ));
11 /* multiply by 1 to strip precision errors (eg 0 != 0) */
12 /* but ONLY if not missing, else will lose any special missing values */
13 &sep put(md5(trim(put(ifn(missing(&var),&var,&var*1),binary64.))),$hex32.)
14 %let sep=!!;
15 %END;
16),$hex32.)
17%mend mp_md5;
This material is provided "as is" by We Are Cas. There are no warranties, expressed or implied, as to merchantability or fitness for a particular purpose regarding the materials or code contained herein. We Are Cas is not responsible for errors in this material as it now exists or will exist, nor does We Are Cas provide technical support for it.
Copyright Info : Main author mentioned: Allan Bowe. One of the referenced files (_version.sas) mentions: Copyright (c) 2001-2006 Rodney Sparapani, licensed under the GNU General Public License.