Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

hex values in haskell

Tags:

haskell

I have the following code in haskell that i want to make some changes to it:

 unwords . map (printf "%02X") $ zipWith (\x y -> -(fromIntegral (ord x)) + y - 2 :: Word8) "Aa123456" [0..]

After running this code i get:

"BD 9E CF CF CF CF CF CF"

Basically i want the inverse of this function, so the function can get the hex values "BD 9E CF CF CF CF CF CF" and return "Aa123456".

I am sure i would have to change the printf statement but how i am suppose to change the script to accept the hex values ?

like image 207
Hanan N. Avatar asked May 27 '26 08:05

Hanan N.


1 Answers

As @gspr suggests, the way to solve this is to break it into smaller parts:

  1. isolating each hexadecimal from the string, i.e. turning "BD 9E CF CF CF CF CF CF" into ["BD", "9E", ...., "CF", "CF"].
  2. converting a hexadecimal string into an integer, e.g. "BD" -> 189
  3. converting each integer into the appropriate character, e.g. 189 -> "A"

For 1, the words function might help.

For 2, read "0xBD" == 189. You just need to work out how to get each hexadecimal number into the right format for read. (Note, that you could also write your conversion function to go directly from string to integer, it might be a nice little bit of practice.)

For 3, just invert the encoding operation, i.e.: write your equation i = y - x - 2 (mod 256) (where i is the one converted from hexadecimal, and y is the index in the list, and x is the value of the character) and solve for x. And chr is the inverse to ord.

like image 172
huon Avatar answered May 30 '26 05:05

huon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!