Skip to content

Instantly share code, notes, and snippets.

@joachimmetz
Last active August 29, 2015 14:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joachimmetz/64513b2d0855c4b43ce0 to your computer and use it in GitHub Desktop.
Save joachimmetz/64513b2d0855c4b43ce0 to your computer and use it in GitHub Desktop.
Python functions to convert a hexadecimal strings.
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2014, Joachim Metz <joachim.metz@gmail.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Python functions to convert a hexadecimal strings."""
def HexStr2Bin(hexstring, separator='-'):
"""Python function to convert a hexadecimal string into a binary stream."""
if not separator:
raise ValueError('Missing separator.')
bytestring = ''
for hexchar in hexstring.split(separator):
bytestring += hexchar.decode('hex')
return bytestring
def HexStr2Guid(hexstring, separator=' '):
"""Python function to convert a hexadecimal string into a GUID string."""
if not separator:
raise ValueError('Missing separator.')
hexlist = [int(x, 16) for x in hexstring.split(separator)]
return '{3:02x}{2:02x}{1:02x}{0:02x}-{5:02x}{4:02x}-{7:02x}{6:02x}-{8:02x}{9:02x}-{10:02x}{11:02x}{12:02x}{13:02x}{14:02x}{15:02x}'.format(*hexlist)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment