Unsigned to signed, error?...

Hi guys...
Macbook Pro, 13", circa August 2012, OSX 10.7.5, default bash terminal.

I require the capability to convert +32767 to -32768 into signed hex words...
The example piece code below works perfectly except...

#/bin/bash
# sign.sh
# Unsign to sign...
while true
do
	# I have used $(( ~n )), where n is a positive integer too.
	# Test piece only hence no error checking at all.
	read -p "Enter negative number -1 to -32768:- " num
	if [ $num -le -1 ]
	then
		printf "$[ ( $num + 65536 ) ]\n"
	else
		printf "Zero or positive value entered, $num.\n"
	fi
	# Why a 64 bit _hex_ value here?
	hex=$(printf "%04X\n" $num)
	printf "$hex\n"
	# I have to use this to correct.
	if [ ${#hex} -gt 4 ]
	then
		hex="${hex:$[ ( ${#hex} - 4 ) ]:4}"
	fi
	printf "$hex\n"
done

Results:-

Last login: Sun Jun  8 19:52:33 on ttys000
AMIGA:barrywalker~> ./sign.sh
Enter negative number -1 to -32768:- 0
Zero or positive value entered, 0.
0000
0000
Enter negative number -1 to -32768:- 1
Zero or positive value entered, 1.
0001
0001
Enter negative number -1 to -32768:- -1
65535
FFFFFFFFFFFFFFFF
FFFF
Enter negative number -1 to -32768:- 32767
Zero or positive value entered, 32767.
7FFF
7FFF
Enter negative number -1 to -32768:- -32768
32768
FFFFFFFFFFFF8000
8000
Enter negative number -1 to -32768:- ^CAMIGA:barrywalker~> 
AMIGA:barrywalker~> _

My question is this:-
Why does the line hex=$(printf "%04X\n" $num) not truncate the hex
string to 4 characters?
I have tried, %04X, %02X and %X along with $num and "$num" but I still have to use the extra code to correct to 4 hex characters.

TIA...

The printf utility (like the C printf() ), never truncates integral numeric values. You can however use a logical and operation to truncate the value:

printf "%04X\n" $((num & 0xFFFF))
1 Like

Hi Don...

Terrific.
I searched everywhere and could not find a solution so had to go back to first principles...
Thanks a lot...

EDIT:

I forgot to add, I didn't know that the shell could do that but on seeing it I immediately understood what it is doing.
Thanks again...