nitin_cherian
nitin_cherian

Reputation: 6675

shell script to convert date to hex format

I have a tool which requires the time in hex format.

Suppose if date -d "Thu Sep 15 09:13:05 UTC 2011" +%s -u gives the time in seconds as 1316077985, the hex value of 1316077985 which is 4E71C1A1 should be found and it should be given as input to the tool as

/usr/bin/mytool 0xA1 0xC1 0x71 0x4E.

How can do this in shell script if the time in seconds is available as input?

Upvotes: 1

Views: 1201

Answers (2)

pgl
pgl

Reputation: 8011

Something like this should work for you:

hex=$(printf '%X' 1316077985)
/usr/bin/mytool  0x${hex:6:2} 0x${hex:4:2} 0x${hex:2:2} 0x${hex:0:2}

Upvotes: 2

fge
fge

Reputation: 121780

I have a solution but it is perl, not shell:

fg@erwin ~/src/json-schema-validator $ date +%s | perl -e 'my $num = <STDIN>; my @hex; while ($num) { push @hex, sprintf("0x%02x", $num & 0xff); $num >>= 8; } print join(", ", reverse @hex) . "\n"'
0x4e, 0xe9, 0xec, 0x88

Upvotes: 0

Related Questions