{"id":23368,"date":"2023-04-15T00:41:57","date_gmt":"2023-04-14T19:11:57","guid":{"rendered":"https:\/\/java2blog.com\/?p=23368"},"modified":"2023-11-09T19:45:15","modified_gmt":"2023-11-09T14:15:15","slug":"python-hex-to-string","status":"publish","type":"post","link":"https:\/\/java2blog.com\/python-hex-to-string\/","title":{"rendered":"Convert Hex to String in Python"},"content":{"rendered":"<div id=\"toc_container\" class=\"toc_light_blue no_bullets\"><p class=\"toc_title\">Table of Contents<\/p><ul class=\"toc_list\"><li><a href=\"#1_Introduction\">1. Introduction<\/a><\/li><li><a href=\"#2_Using_bytesfromhex_Method\">2. Using bytes.fromhex() Method<\/a><\/li><li><a href=\"#3_Using_binascii_Module\">3. Using binascii Module<\/a><\/li><li><a href=\"#4_Using_codecs_Module\">4. Using codecs Module<\/a><\/li><li><a href=\"#5_Using_List_Comprehension\">5. Using List Comprehension<\/a><\/li><li><a href=\"#6_Conclusion\">6. Conclusion<\/a><\/li><\/ul><\/div>\n<h2><span id=\"1_Introduction\">1. Introduction<\/span><\/h2>\n<p>The representation of data in Hexadecimal is commonly used in computer programming.  It is used to represent binary data in a human-readable form, as understanding the machine language (i.e., Binary) is difficult for humans. Hexadecimal notation is used in networking protocols, e.g., IPv6 and cryptography, and widely used in graphics, e.g. to represent numbers. <strong>Note that hexadecimal uses <code>16<\/code> digits, including <code>0-9 and A-F<\/code>, to represent numbers.<\/strong><\/p>\n<p>Considering the importance of hexadecimal, some programming languages and APIs require string representation of binary data. As a lot of data is in hexadecimal form, so we need to convert the hexadecimal number to a string. This conversion helps to display and manipulate the <code>binary<\/code> data as <code>text<\/code>, which makes the task more convenient for humans.<\/p>\n<blockquote>\n<p>In python language, there are different ways to convert Hex to String.<\/p>\n<p><strong>Method 1: Using <code>bytes.fromhex()<\/code> method<\/strong><\/p>\n<pre code=\"python\" title=\"Using bytes.fromhex() Method\" mark=\"3\">\nbyte_str = bytes.fromhex(hex_str)            #Convert hex string to bytes\nregular_str = byte_str.decode('utf-8')       #Convert bytes to regular string\n<\/pre>\n<p><strong>Method 2: Using <code>binascii<\/code> module<\/strong><\/p>\n<pre code=\"python\" title=\"Using binascii module\" mark=\"3\">\nbyte_str = binascii.unhexlify(hex_str)           # Convert hex string to bytes\nregular_str = byte_str.decode('utf-8')           # Convert bytes to regular string\n<\/pre>\n<p><strong>Method 3:  Using <code>codecs<\/code> module<\/strong><\/p>\n<pre code=\"python\" title=\"Using codec module\" mark=\"3\">\nbyte_str = binascii.unhexlify(hex_str)           # Convert hex string to bytes\nregular_str = byte_str.decode('utf-8')           # Convert bytes to regular string\n<\/pre>\n<p><strong>Method 4:  Using List comprehension<\/strong><\/p>\n<pre code=\"python\" title=\"Using List Comprehension\" mark=\"2\">\nregular_str = ''.join([chr(int(hex_str[i:i+2], 16)) for i in range(0, len(hex_str), 2)])\n<\/pre>\n<\/blockquote>\n<p>Let&#8217;s go through each method in detail.<\/p>\n<h2><span id=\"2_Using_bytesfromhex_Method\">2. Using bytes.fromhex() Method<\/span><\/h2>\n<p><strong>Use the <code>bytes.fromhex()<\/code> method to convert a hexadecimal string to a simple string in Python.<\/strong><\/p>\n<pre code=\"python\" title=\"Use bytes.fromhex() Method\" mark=\"3\">\nhex_str = \"48656c6c6f20576f726c64\"           #Hex string\nbyte_str = bytes.fromhex(hex_str)            #Convert hex string to bytes\nregular_str = byte_str.decode('utf-8')       #Convert bytes to regular string\nprint(regular_str)                           #Print Output                                 \n<\/pre>\n<pre title=\"Output\">\nHello World \n<\/pre>\n<p>First, the <code>hex_str<\/code>  is defined, which contains a sequence of characters representing a hexadecimal number. After that, the  <code>bytes.fromhex()<\/code> method is called with <code>hex_str<\/code> as its argument that converts the string of hexadecimal characters into a byte object. The resulting <code>byte_str<\/code> variable contains the byte values represented by the hexadecimal characters.<\/p>\n<p>The  <code>decode()<\/code> method is called on the <code>byte_str<\/code> variable with <code>&#039;utf-8&#039;<\/code> as its argument. This method converted the bytes object into a regular string using the UTF-8 encoding. The resulting <code>regular_str<\/code> variable contains the <code>&quot;Hello World&quot;<\/code> string. Finally, the <code>regular_str<\/code> variable is printed to the console using the <code>print()<\/code> function.<\/p>\n<h2><span id=\"3_Using_binascii_Module\">3. Using binascii Module<\/span><\/h2>\n<p><strong>The <code>binascii<\/code> Module can be used for hex to String conversion. It follows the same steps as required for the above method. The main difference is at the point of converting a hexadecimal string to bytes.<\/strong><\/p>\n<pre code=\"python\" title=\"Use the binascii Module\" mark=\"4\">\nimport binascii                                  #Import module\nhex_str = \"48656c6c6f20576f726c64\"               # Hex string\nbyte_str = binascii.unhexlify(hex_str)           # Convert hex string to bytes\nregular_str = byte_str.decode('utf-8')           # Convert bytes to regular string\nprint(regular_str)                               # Print Output\n<\/pre>\n<pre title=\"Output\">\nHello World \n<\/pre>\n<p>In this example, first, we imported the <code>binascii<\/code> module, which provides functions for converting between binary and ASCII formats.  Then, the <code>unhexlify()<\/code> function converts the hex string to a bytes object. Finally,  the bytes object is converted to a regular string using the <code>decode()<\/code> method and printed to the console.<\/p>\n<h2><span id=\"4_Using_codecs_Module\">4. Using codecs Module<\/span><\/h2>\n<p><strong>The <code>codecs<\/code>&#8216;s decode() method can be used for python hex to String conversion. It takes two arguments &#8211; bytes object and encoding type<\/strong><\/p>\n<pre code=\"python\" title=\"Use the binascii Module\" mark=\"6\">\nimport codecs                                     #Import module\n\nhex_str = \"48656c6c6f20576f726c64\" \nhex_str_bytes = bytes(hex_str, encoding='utf-8') # Convert hex string to bytes\nbinary_string = codecs.decode(hex_str_bytes, \"hex\") # Convert bytes to regular string\nprint(str(binary_string, 'utf-8'))\n\n<\/pre>\n<pre title=\"Output\">\nHello World \n<\/pre>\n<p>In this example, first, we imported the <code>codecs<\/code> module. Then, the <code>bytes()<\/code> function converts the hex string to a bytes object. Finally,  the bytes object is converted to a regular string using the <code>decode()<\/code> method and printed to the console.<\/p>\n<section class=\"read-more-posts\">\n<div class=\"rm-header\">\n<h2>Further reading:<\/h2>\n<\/div>\n<div class=\"rm-wrap\">\n<div class=\"rm-item\">\n<h5><a href=\"https:\/\/java2blog.com\/python-hex-to-int\/\" target=\"_blank\" rel=\"noopener\">Python hex to int<\/a><\/h5>\n<div class=\"ex\">\n            <a href=\"https:\/\/java2blog.com\/python-hex-to-int\/\" target=\"_blank\" rel=\"noopener\">Read more \u2192<\/a>\n        <\/div>\n<\/div>\n<div class=\"rm-item\">\n<h5><a href=\"https:\/\/java2blog.com\/print-int-as-hex-python\/\" target=\"_blank\" rel=\"noopener\">Print int as hex in Python<\/a><\/h5>\n<div class=\"ex\">\n            <a href=\"https:\/\/java2blog.com\/print-int-as-hex-python\/\" target=\"_blank\" rel=\"noopener\">Read more \u2192<\/a>\n        <\/div>\n<\/p><\/div>\n<\/div>\n<\/section>\n<h2><span id=\"5_Using_List_Comprehension\">5. Using List Comprehension<\/span><\/h2>\n<p><strong>Use list comprehension to convert hexadecimal to string in Python. Unlike the above methods, the hexadecimal string is not converted into bytes but into a decimal integer.<\/strong> <\/p>\n<pre code=\"python\" title=\"Use List Comprehension\">\n#Hex string\nhex_str = \"48656c6c6f20576f726c64\"\n\n#loop over the hexadecimal string to convert to\n#a decimal integer and join the respective ASCII character\nregular_str = ''.join([chr(int(hex_str[i:i+2], 16)) for i in range(0, len(hex_str), 2)])\n\n#Print Output\nprint(regular_str)                               \n<\/pre>\n<pre title=\"Output\">\nHello World \n<\/pre>\n<p>The list comprehension converted each pair of hexadecimal characters into a decimal integer using the <code>int()<\/code> function for this code. Then, the integer was converted to its corresponding ASCII character using the <code>chr()<\/code> function. Finally, joined the resulting list of characters into a single string using the <code>join()<\/code> method.<\/p>\n<p><strong> Please note that this method works for hex strings that have even number of digits and do not have prefix <code>0x.<\/code><\/strong><\/p>\n<h2><span id=\"6_Conclusion\">6. Conclusion<\/span><\/h2>\n<p>All four methods produced the same output: the string <code>&quot;Hello World&quot;<\/code> as the input string was the same. Therefore, you can try different hexadecimal strings and convert them into regular strings using the above methods. <\/p>\n","protected":false},"excerpt":{"rendered":"<p>Table of Contents1. Introduction2. Using bytes.fromhex() Method3. Using binascii Module4. Using codecs Module5. Using List Comprehension6. Conclusion 1. Introduction The representation of data in Hexadecimal is commonly used in computer programming. It is used to represent binary data in a human-readable form, as understanding the machine language (i.e., Binary) is difficult for humans. Hexadecimal notation [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":23762,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"inline_featured_image":false,"_mi_skip_tracking":false},"categories":[186,145],"tags":[],"_links":{"self":[{"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/posts\/23368"}],"collection":[{"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/comments?post=23368"}],"version-history":[{"count":10,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/posts\/23368\/revisions"}],"predecessor-version":[{"id":25350,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/posts\/23368\/revisions\/25350"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/media\/23762"}],"wp:attachment":[{"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/media?parent=23368"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/categories?post=23368"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/tags?post=23368"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}