views:

402

answers:

3

When using the Windows set /p and set /a commands to accept a hexadecimal value from the command line and convert it to decimal. What I need is to be able to take a decimal value and set and environment variable with its hexadecimal equivalent.

Current batch file coding:

@echo off
set HexV1=%1
set HexV2=%2
set /A DecV1=0x%HexV1%
set /A DecV2=0x%HexV2%
set /A HexV3=0x%HexV1% + 0x1
set /A HexV4=0x%Hexv2% + 0x2
set Dec
set Hex

Produces:

C:>hexmath a f
DecV1=10
DecV2=15
HexV1=a
HexV2=f
HexV3=11
HexV4=17

What I need is to be able to set HexV3 to b and HexV4 to 11.

Any suggestions?

A: 

This forum post at channel9.msdn.com has a batch script that will convert from integer to hex.

If has a loop using a GOTO and processes the number using the modulo - SET /A & % - and integer division - SET /A & / - operators and some IF statements to build up the hex string.

Dave Webb
+4  A: 

The batch file on channel9 was much to long for my tastes. Here's a simpler (IMO) version of "tohex.bat" that I just whipped up:

@echo off & setlocal ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION
set LOOKUP=0123456789abcdef &set HEXSTR=&set PREFIX=
if "%1"=="" echo 0&goto :EOF
set /a A=%*
if !A! LSS 0 set /a A=0xfffffff + !A! + 1 & set PREFIX=f
:loop
set /a B=!A! %% 16 & set /a A=!A! / 16
set HEXSTR=!LOOKUP:~%B%,1!%HEXSTR%
if %A% GTR 0 goto :loop
echo %PREFIX%%HEXSTR%

It works in much the same way as the other script (iteratively dividing by 16), but it uses a string lookup (instead of a series of "if" statements) to build the hex string. It handles negative numbers as well (two's complement), but it's a bit of a hack.

You could call it from your other batch file like so:

for /f "delims=" %%Q IN ('call tohex.bat 0x%HexV1% + 0x1') DO SET HexV3=%%Q

Hope that helps.

ijprest
+1. Nice one. And makes me sad that I didn't write it :-)
Joey
That string lookup is very neat.
Dave Webb
A: 

Thank you very much! This has solved my issues.

Robert Gardner