w3resource

Hexadecimal values of list elements using memory views in Python


10. Memory View from List to Hex

Write a Python program that creates a memory view from a list of integers and print the hex values of each element.

Sample Solution:

Code:

def test(memory_view):
    for element in memory_view:
        print(hex(element))

def main():
    nums = [8, 16, 42, 92, 128]
    print("Original list values:",nums)

    # Create a memory view from the list of integers
    memory_view = memoryview(bytearray(nums))

    print("Hex Values of said list elements:")
    test(memory_view)

if __name__ == "__main__":
    main()

Output:

Original list values: [8, 16, 42, 92, 128]
Hex Values of said list elements:
0x8
0x10
0x2a
0x5c
0x80

Flowchart:

Flowchart: Hexadecimal values of list elements using memory views in Python.

For more Practice: Solve these Related Problems:

  • Write a Python program to create a memory view from a list of integers, then iterate over the view and print each element’s hexadecimal value.
  • Write a Python function to convert a list of integers to a bytes object, form a memory view, and then output the hex representation of each byte.
  • Write a Python script to build a memory view from a list of integers and then use a loop to display the hex value of every element in the view.
  • Write a Python program to accept a list of integers, create a memory view from it, and then print the concatenated hexadecimal string of all elements.

Python Code Editor :

Previous: Slicing memory views in Python: Indexing syntax and example.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.