[image] GolamMostafa: can it be used as a variable? No. You define a variable with the data type char. char myVariable; Answer from Grumpy_Mike on forum.arduino.cc
🌐
Binary Hex Decimal Converter
binaryhexconverter.com
Binary Hex Decimal Converter Calculator
Binaryhexconverter is a handy set of online binary converter tools including binary, decimal, hexadecimal, ascii text and octal base calculator.
🌐
SCADACore
scadacore.com › home › tools › programming calculators › online hex converter
Online Hex Converter - Bytes, Ints, Floats, Significance, Endians - SCADACore
April 8, 2021 - Online Hex Converter This is a free online hex converter that converts hex values into bytes, ints, and floats of different bit significance. With millions of different sensors and devices that will be connected to the cloud for IIoT, determining the
🌐
Arduino Forum
forum.arduino.cc › projects › programming
Converting from byte to a HEX variable - Programming - Arduino Forum
March 21, 2023 - Hi with my serial input, I am getting bytes and can print them as Serial.print(gotByte) or Serial.print(gotByte,HEX) or Serial.print(gotByte.HEX) and they print correctly. BUT how do I convert the gotByte into a variab…
Discussions

How do you convert a byte array to a hexadecimal string in C? - Stack Overflow
In the context of the question ... to convert to hexadecimal is well known (I could have put some hardcoded 4 instead of sizeof). In the general case the function should be called on some input of known length and the target buffer have 3 times + 1 bytes availab... More on stackoverflow.com
🌐 stackoverflow.com
Understanding bytes and hex
In traditional computing and networking all data is stored or transferred as binary. Binary is representative of an electrical state. When transferring data across the wire for example, a one is represented by a high (5v DC) and a zero is low (0v dc). You can think of this as on vs off. So it’s the same for magnetic media... the point on the platter is either in an on state (1) or off state (0). Hex is not what the data looks like in its storage state. Hex is a different method of “notation”. So I can take a byte and represent it in decimal notation like 10101010 or a shorten it by representing it as “aa”. Depending on the kernel and os or application, data is interpreted in many different ways. What the pen tester was doing was manipulating specific file header bytes. Which in their method could be “expressed” as hex. It would still be 1’s and 0’s at its lowest level as bits on disk. It’s most important that you under stand that depending on the layer that you are looking at data will be expressed in several different ways. The ascii character “a” is still bits on disk somewhere... but you don’t see it in decimal notation right? Hope that helps... Cheers! More on reddit.com
🌐 r/hacking
8
3
November 18, 2019
arrays - How to convert hexadecimal string to bytes in Python? - Stack Overflow
I have a long Hex string that represents a series of values of different types. I need to convert this Hex String into bytes or bytearray so that I can extract each value from the raw data. How can... More on stackoverflow.com
🌐 stackoverflow.com
c# - byte[] to hex string - Stack Overflow
How do I convert a byte[] to a string? Every time I attempt it, I get System.Byte[] instead of the value. Also, how do I get the value in Hex instead of a decimal? More on stackoverflow.com
🌐 stackoverflow.com
Top answer
1 of 16
123
printf("%02X:%02X:%02X:%02X", buf[0], buf[1], buf[2], buf[3]);

For a more generic way:

int i;
for (i = 0; i < x; i++)
{
    if (i > 0) printf(":");
    printf("%02X", buf[i]);
}
printf("\n");

To concatenate to a string, there are a few ways you can do this. I'd probably keep a pointer to the end of the string and use sprintf. You should also keep track of the size of the array to make sure it doesn't get larger than the space allocated:

int i;
char* buf2 = stringbuf;
char* endofbuf = stringbuf + sizeof(stringbuf);
for (i = 0; i < x; i++)
{
    /* i use 5 here since we are going to add at most 
       3 chars, need a space for the end '\n' and need
       a null terminator */
    if (buf2 + 5 < endofbuf)
    {
        if (i > 0)
        {
            buf2 += sprintf(buf2, ":");
        }
        buf2 += sprintf(buf2, "%02X", buf[i]);
    }
}
buf2 += sprintf(buf2, "\n");
2 of 16
47

For completude, you can also easily do it without calling any heavy library function (no snprintf, no strcat, not even memcpy). It can be useful, say if you are programming some microcontroller or OS kernel where libc is not available.

Nothing really fancy you can find similar code around if you google for it. Really it's not much more complicated than calling snprintf and much faster.

#include <stdio.h>

int main(){
    unsigned char buf[] = {0, 1, 10, 11};
    /* target buffer should be large enough */
    char str[12];

    unsigned char * pin = buf;
    const char * hex = "0123456789ABCDEF";
    char * pout = str;
    int i = 0;
    for(; i < sizeof(buf)-1; ++i){
        *pout++ = hex[(*pin>>4)&0xF];
        *pout++ = hex[(*pin++)&0xF];
        *pout++ = ':';
    }
    *pout++ = hex[(*pin>>4)&0xF];
    *pout++ = hex[(*pin)&0xF];
    *pout = 0;

    printf("%s\n", str);
}

Here is another slightly shorter version. It merely avoid intermediate index variable i and duplicating laste case code (but the terminating character is written two times).

#include <stdio.h>
int main(){
    unsigned char buf[] = {0, 1, 10, 11};
    /* target buffer should be large enough */
    char str[12];

    unsigned char * pin = buf;
    const char * hex = "0123456789ABCDEF";
    char * pout = str;
    for(; pin < buf+sizeof(buf); pout+=3, pin++){
        pout[0] = hex[(*pin>>4) & 0xF];
        pout[1] = hex[ *pin     & 0xF];
        pout[2] = ':';
    }
    pout[-1] = 0;

    printf("%s\n", str);
}

Below is yet another version to answer to a comment saying I used a "trick" to know the size of the input buffer. Actually it's not a trick but a necessary input knowledge (you need to know the size of the data that you are converting). I made this clearer by extracting the conversion code to a separate function. I also added boundary check code for target buffer, which is not really necessary if we know what we are doing.

#include <stdio.h>

void tohex(unsigned char * in, size_t insz, char * out, size_t outsz)
{
    unsigned char * pin = in;
    const char * hex = "0123456789ABCDEF";
    char * pout = out;
    for(; pin < in+insz; pout +=3, pin++){
        pout[0] = hex[(*pin>>4) & 0xF];
        pout[1] = hex[ *pin     & 0xF];
        pout[2] = ':';
        if (pout + 3 - out > outsz){
            /* Better to truncate output string than overflow buffer */
            /* it would be still better to either return a status */
            /* or ensure the target buffer is large enough and it never happen */
            break;
        }
    }
    pout[-1] = 0;
}

int main(){
    enum {insz = 4, outsz = 3*insz};
    unsigned char buf[] = {0, 1, 10, 11};
    char str[outsz];
    tohex(buf, insz, str, outsz);
    printf("%s\n", str);
}
🌐
Zytrax
zytrax.com › tech › protocols › hex.html
Tech Stuff - Hexadecimal, Decimal and Binary
May 24, 2023 - The following are all valid, and used, bit numbering conventions for describing an 8 bit byte (an octet). Always check what convention is used on any specification. We have bowed to the inevitable and use the Left to right base 0 (IETF) standard since, because of the Internet, it is widely used and, hopefully, equally widely understood.
Find elsewhere
🌐
Wikipedia
en.wikipedia.org › wiki › Hexadecimal
Hexadecimal - Wikipedia
2 days ago - For the most common convention, ... value 10 to 15. As typical computer hardware is binary in nature and 16 is a power of 2, the hex representation is often used in computing as a dense representation of binary information. A hex digit represents 4 contiguous bits–known as a nibble. An 8-bit byte is two hex ...
🌐
Reddit
reddit.com › r/hacking › understanding bytes and hex
r/hacking on Reddit: Understanding bytes and hex
November 18, 2019 -

Ok so i am trying to understand this concept (I have many questions)

Bytes are 1s and 0s, so binary Binary can be translated to hexadecimal So then can bytes be 1s and 0s and hexadecimal, like any of them two, (not sure about that tho)

I was watching a pentesting video on a hackthebox machine, and the guy was trying to change the so called magic bytes of a file so that the system recognized the file as a different file then it actually was, to do that he printed in plain text some hex stuff (which was the file signature in hex) like \xAb\xC3\xf3 etc etc into the file (echo \xAb\xC3\xF3 > file.txt) , so another question is when the computer read all these hex characters, did it import it in the bytes just like that, or did it recognize it has hex and then convert it to binary and then into the bytes

As you see i am very confused with bytes and how they store information, and how you can “insert” information in to bytes, and how all that would work. So if anybody could please explain like im 5 i would appreciate it a lot, as i am just starting to learn all of this stuff

Thank you!!

Ps: I hope you understand my question as I am not very good at explaining myself lol

Top answer
1 of 3
6
In traditional computing and networking all data is stored or transferred as binary. Binary is representative of an electrical state. When transferring data across the wire for example, a one is represented by a high (5v DC) and a zero is low (0v dc). You can think of this as on vs off. So it’s the same for magnetic media... the point on the platter is either in an on state (1) or off state (0). Hex is not what the data looks like in its storage state. Hex is a different method of “notation”. So I can take a byte and represent it in decimal notation like 10101010 or a shorten it by representing it as “aa”. Depending on the kernel and os or application, data is interpreted in many different ways. What the pen tester was doing was manipulating specific file header bytes. Which in their method could be “expressed” as hex. It would still be 1’s and 0’s at its lowest level as bits on disk. It’s most important that you under stand that depending on the layer that you are looking at data will be expressed in several different ways. The ascii character “a” is still bits on disk somewhere... but you don’t see it in decimal notation right? Hope that helps... Cheers!
2 of 3
4
1 bit is a 1 or a 0 so: 1 A byte is 8 bits so:, 11010101 I will come to hex later. So to understand binary you first need to understand decimal which u are using all you life. Decimal has a base of 10 which means each number is a power of 10 so how you calculate 123 is : So anything to the pow of 0 equals 1(except for 0 to the pow of 0) 3 * 10 to the pow of 0 = 3 * 1 = 3 2 * 10 to the pow of 1 = 2 * 10 = 20 1 * 10 to the pow of 2 = 1 * 10 *10 = 100 --> 3 + 20 + 100 = 123 Binary has a base of 2, let's take the example of my byte above: 11010101 The value for each bit from right to left therfore is 1, 2, 4, 8, 16, 32, 64, 128. A 1 means you use the value a 0 means you do not: 1 * 1 = 1 0 * 2 = 0 1 * 4 = 4 0 * 8 = 0 1 * 16 = 16 0 * 32 = 0 1 * 64 = 64 1 * 128 = 128 --> 1 + 4 + 16 + 64 + 128 =213 Now Hof hex values you have a base of 16, the numbers are from 0 - F 0123456789ABCDEF Usually written as 0x1A A 2 digit hex value can hold the same value as a byte(8 bits) that's why it is used so much, it is easier to read for humans and a computer reads it the same as a byte. The hex 0x1A has the value A * 1 = 10 1 * 16 = 16 --> 10 + 16 = 26 So computer turns every number into bits so it does not really matter if you give it a number in binary, decimal or hex it is just another way to read it. If you look for videos on something like "hex to Dec to bin" I am sure you will find some good videos. Hope this helps a bit, wrote it in a train on my phone so sry for typos.
🌐
Baeldung
baeldung.com › home › java › java array › converting between byte arrays and hexadecimal strings in java
Converting Between Byte Arrays and Hexadecimal Strings in Java | Baeldung
March 26, 2025 - First of all, we’ll convert each hexadecimal digit into binary equivalent separately. And then, we need to concatenate the two four bit-segments to get the byte equivalent:
🌐
RapidTables
rapidtables.com › convert › number › hex-to-binary.html
Hex to Binary Converter
Convert every hex digit (start lowest digit) to 4 binary digits, with this table:
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › api › system.convert.fromhexstring
Convert.FromHexString Method (System) | Microsoft Learn
Public Shared Function FromHexString ... As Byte() ... The UTF-8 span to convert. ... An array of 8-bit unsigned integers that is equivalent to utf8Source. ... The length of utf8Source is not zero or a multiple of two. ... The format of utf8Source is invalid -OR- utf8Source contains a non-hex ...
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › api › system.convert.tohexstring
Convert.ToHexString Method (System) | Microsoft Learn
Public Shared Function ToHexString (bytes As ReadOnlySpan(Of Byte)) As String ... A span of 8-bit unsigned integers. ... The string representation in hex of the elements in bytes.
🌐
Spark
spark.money › home › tools › hex converter: hexadecimal to text, decimal, binary, and base64
Hex Converter: Hexadecimal to Text, Decimal, Binary, and Base64 | Spark
The hex system is fundamental to computing because it maps cleanly onto the binary representation that processors actually use. A single hex digit corresponds to a 4-bit nibble, and a pair of hex digits corresponds to a full byte.
Top answer
1 of 16
720

There is a built in method for this:

byte[] data = { 1, 2, 4, 8, 16, 32 };

string hex = BitConverter.ToString(data);

Result: 01-02-04-08-10-20

If you want it without the dashes, just remove them:

string hex = BitConverter.ToString(data).Replace("-", string.Empty);

Result: 010204081020

If you want a more compact representation, you can use Base64:

string base64 = Convert.ToBase64String(data);

Result: AQIECBAg

2 of 16
128

.Net5.0 Update

Thanks to @antoninkriz's benchmark comparison we can see that Convert.ToHexString is by far the clear winner today

You'd be foolish to use anything other than Convert.ToHexString. In my opinion it clearly wins in: readability, performance, safety


The rest of this is from before Apr 10, 2012:

I thought I would attempt to compare the speed of each of the methods listed here for the hell of it. I based the speed testing code off this.

The result is that BitConverter+String.Replace seems to be faster than most other simple ways. But the speed can be improved with algorithms like Nathan Moinvaziri's ByteArrayToHexString or Kurt's ToHex.

I also found it interesting that string.Concat and string.Join are much slower than StringBuilder implementations for long strings, but similar for shorter arrays. Probably due to expanding the StringBuilder on the longer strings, so setting the initial size should negate this difference.

  • Took each bit of code from an answer here:
  • BitConvertRep = Answer by Guffa, BitConverter and String.Replace (I'd recommend for most cases, [edit:] where you can't use Convert.ToHexString)
  • StringBuilder = Answer by Quintin Robinson, foreach char StringBuilder.Append
  • LinqConcat = Answer by Michael Buen, string.Concat of Linq built array
  • LinqJoin = Answer by mloskot, string.Join of Linq built array
  • LinqAgg = Answer by Matthew Whited, IEnumerable.Aggregate with StringBuilder
  • ToHex = Answer by Kurt, sets chars in an array, using byte values to get hex
  • ByteArrayToHexString = Answer by Nathan Moinvaziri, approx same speed as the ToHex above, and is probably easier to read (I'd recommend for speed, [edit:] where you can't use Convert.ToHexString)
  • ToHexFromTable = Linked in answer by Nathan Moinvaziri, for me this is near the same speed as the above 2 but requires an array of 256 strings to always exist

With: LONG_STRING_LENGTH = 1000 * 1024;

  • BitConvertRep calculation Time Elapsed 27,202 ms (fastest built in/simple)
  • StringBuilder calculation Time Elapsed 75,723 ms (StringBuilder no reallocate)
  • LinqConcat calculation Time Elapsed 182,094 ms
  • LinqJoin calculation Time Elapsed 181,142 ms
  • LinqAgg calculation Time Elapsed 93,087 ms (StringBuilder with reallocating)
  • ToHex calculation Time Elapsed 19,167 ms (fastest)

With: LONG_STRING_LENGTH = 100 * 1024;, Similar results

  • BitConvertReplace calculation Time Elapsed 3431 ms
  • StringBuilder calculation Time Elapsed 8289 ms
  • LinqConcat calculation Time Elapsed 21512 ms
  • LinqJoin calculation Time Elapsed 19433 ms
  • LinqAgg calculation Time Elapsed 9230 ms
  • ToHex calculation Time Elapsed 1976 ms

With: int MANY_STRING_COUNT = 1000; int MANY_STRING_LENGTH = 1024; (Same byte count as first test but in different arrays)

  • BitConvertReplace calculation Time Elapsed 25,680 ms
  • StringBuilder calculation Time Elapsed 78,411 ms
  • LinqConcat calculation Time Elapsed 101,233 ms
  • LinqJoin calculation Time Elapsed 99,311 ms
  • LinqAgg calculation Time Elapsed 84,660 ms
  • ToHex calculation Time Elapsed 18,221 ms

With: int MANY_STRING_COUNT = 2000; int MANY_STRING_LENGTH = 20;

  • BitConvertReplace calculation Time Elapsed 1347 ms
  • StringBuilder calculation Time Elapsed 3234 ms
  • LinqConcat calculation Time Elapsed 5013 ms
  • LinqJoin calculation Time Elapsed 4826 ms
  • LinqAgg calculation Time Elapsed 3589 ms
  • ToHex calculation Time Elapsed 772 ms

Testing code I used:

void Main()
{
    int LONG_STRING_LENGTH = 100 * 1024;
    int MANY_STRING_COUNT = 1024;
    int MANY_STRING_LENGTH = 100;

    var source = GetRandomBytes(LONG_STRING_LENGTH);

    List<byte[]> manyString = new List<byte[]>(MANY_STRING_COUNT);
    for (int i = 0; i < MANY_STRING_COUNT; ++i)
    {
        manyString.Add(GetRandomBytes(MANY_STRING_LENGTH));
    }

    var algorithms = new Dictionary<string,Func<byte[], string>>();
    algorithms["BitConvertReplace"] = BitConv;
    algorithms["StringBuilder"] = StringBuilderTest;
    algorithms["LinqConcat"] = LinqConcat;
    algorithms["LinqJoin"] = LinqJoin;
    algorithms["LinqAgg"] = LinqAgg;
    algorithms["ToHex"] = ToHex;
    algorithms["ByteArrayToHexString"] = ByteArrayToHexString;

    Console.WriteLine(" === Long string test");
    foreach (var pair in algorithms) {
        TimeAction(pair.Key + " calculation", 500, () =>
        {
            pair.Value(source);
        });
    }

    Console.WriteLine(" === Many string test");
    foreach (var pair in algorithms) {
        TimeAction(pair.Key + " calculation", 500, () =>
        {
            foreach (var str in manyString)
            {
                pair.Value(str);
            }
        });
    }
}

// Define other methods and classes here
static void TimeAction(string description, int iterations, Action func) {
    var watch = new Stopwatch();
    watch.Start();
    for (int i = 0; i < iterations; i++) {
        func();
    }
    watch.Stop();
    Console.Write(description);
    Console.WriteLine(" Time Elapsed {0} ms", watch.ElapsedMilliseconds);
}

//static byte[] GetRandomBytes(int count) {
//  var bytes = new byte[count];
//  (new Random()).NextBytes(bytes);
//  return bytes;
//}
static Random rand = new Random();
static byte[] GetRandomBytes(int count) {
    var bytes = new byte[count];
    rand.NextBytes(bytes);
    return bytes;
}


static string BitConv(byte[] data)
{
    return BitConverter.ToString(data).Replace("-", string.Empty);
}
static string StringBuilderTest(byte[] data)
{
    StringBuilder sb = new StringBuilder(data.Length*2);
    foreach (byte b in data)
        sb.Append(b.ToString("X2"));

    return sb.ToString();
}
static string LinqConcat(byte[] data)
{
    return string.Concat(data.Select(b => b.ToString("X2")).ToArray());
}
static string LinqJoin(byte[] data)
{
    return string.Join("",
        data.Select(
            bin => bin.ToString("X2")
            ).ToArray());
}
static string LinqAgg(byte[] data)
{
    return data.Aggregate(new StringBuilder(),
                               (sb,v)=>sb.Append(v.ToString("X2"))
                              ).ToString();
}
static string ToHex(byte[] bytes)
{
    char[] c = new char[bytes.Length * 2];

    byte b;

    for(int bx = 0, cx = 0; bx < bytes.Length; ++bx, ++cx)
    {
        b = ((byte)(bytes[bx] >> 4));
        c[cx] = (char)(b > 9 ? b - 10 + 'A' : b + '0');

        b = ((byte)(bytes[bx] & 0x0F));
        c[++cx] = (char)(b > 9 ? b - 10 + 'A' : b + '0');
    }

    return new string(c);
}
public static string ByteArrayToHexString(byte[] Bytes)
{
    StringBuilder Result = new StringBuilder(Bytes.Length*2);
    string HexAlphabet = "0123456789ABCDEF";

    foreach (byte B in Bytes)
        {
        Result.Append(HexAlphabet[(int)(B >> 4)]);
        Result.Append(HexAlphabet[(int)(B & 0xF)]);
        }

    return Result.ToString();
}

Also another answer with a similar process, I haven't compared our results yet.

🌐
Reddit
reddit.com › r/learnpython › how to convert a large string having hex digits into bytes?
r/learnpython on Reddit: How to convert a large string having Hex digits into bytes?
February 28, 2026 -

What I'm trying to do is convert a string like "abcd" into bytes that represent the hexadecimal of the string oxabcd. Python keeps telling me OverflowError: int too big to convert

The code is the following:

a = "abcd"

print(int(a, 16).to_bytes())

The error in full is:

Traceback (most recent call last):
  File "/home/repl109/main.py", line 6, in <module>
    print(int(a, 16).to_bytes())
        ^^^^^^^^^^^^^^^^^^^^^
OverflowError: int too big to convert

Anyone know a way to do this for large integers?

🌐
Cryptii
cryptii.com › pipes › hex-to-base64
Hex to Base64: Encode and decode bytes online - cryptii
Base64 encoding schemes are used when binary data needs to be stored or transferred as textual data. Therefore 64 characters are chosen that are both members of a subset common to most encodings (ASCII), and also printable.
🌐
NI Community
forums.ni.com › community › discussion forums › most active software boards › labview › convert hexadecimal string to byte array
Solved: Convert Hexadecimal String to Byte Array - NI Community
October 1, 2014 - As a sample VI, control accepting hex string directly, otherwise LabVIEW will perform the ASCI conversion. Second, I haven't considered the length as odd or even. It always segregates from least significant bytes. ... This is what exactly the "String To Byte Array" function does.
🌐
Base64.Guru
base64.guru › home › base64 converter › base64 decode
Base64 to Hex | Base64 Decode | Base64 Converter | Base64
Hi Frank Thanks for the code. I would like to implement this in a google sheet. We are forwarding data in hex format that is base64 encoded from the Things Networks to Pipedream and then into google sheets. How would I add your code to the script editor in google sheets to decode our data?