What is fastest way to convert bool to byte?

convert bool to byte array c#
c# convert bool to bit
bool to byte golang
cannot convert bool to sbyte
bool to binary c#
c# hex literal

What is fastest way to convert bool to byte?

I want this mapping: False=0, True=1

Note: I don't want to use any if statements or other conditional statements. I don't want the CPU to halt or guess next statement.

Update: For those who want to see the point of this question. This example shows how two if statement are reduced from the code.

byte A = k > 9 ; //If it was possible (k>9) == 0 || 1
c[i * 2] = A * (k + 0x37) - (A - 1) * (k + 0x30);

Using unsafe code this method is pretty fast. With optimizations enabled its about 30% faster than the conditional operator.

bool input = true;
byte value = *((byte*)(&input)); // 1

Convert Boolean to Byte in C#, A byte is an 8-bit unsigned integer. The ToByte method of the Convert class converts other base data types to a byte data type. Convert a Boolean  Use Convert.ToInt32. There are no 4-byte bools, the type only needs 1 bit. 4 or 8 bytes are used for a bool though because that's the word size in a 32 or 64-bit OS. – Panagiotis Kanavos May 24 '19 at 13:46

How about:

byte x = value ? (byte) 1 : (byte) 0;

If you're talking about the most efficient way of doing it, there may be some tricks you could do with unsafe code... but is this really a bottleneck for you?

EDIT: I just realized that the conditional operator needs those casts for the operands in order to make the overall expression a byte.

EDIT: Having seen your question, there's a much better way of optimizing it IMO. Currently you'll be performing operations you don't need to either way. Try this instead:

c[i << 1] = k > 9 ? k + 0x37 : k + 0x30;

or

c[i << 1] = k + (k > 9 ? 0x37 : 0x30);

(I suspect it doesn't matter which.)

You only need to perform the comparison and then one addition - instead of two additions and two multiplications after the conversion from bool to byte.

EDIT: Having just tried this, due to potentially branch misses, this can still definitely be slower than the unsafe version... or it can be faster. Picking a random value for k in the range [0, 18), this approach takes twice as long as the unsafe code. Picking a random value for k in the range [0, 1000) (i.e. one branch is picked much more often than the other), this approach is faster than the unconditional one. So what's the pattern for your k value?

Here's some benchmark code:

using System;
using System.Diagnostics;

class Test
{
    static void Main()
    {
        Random rng = new Random();
        int[] ks = new int[100000000];
        for (int i = 0; i < ks.Length; i++)
        {
            ks[i] = rng.Next(1000);
        }

        for (int i = 0; i < 3; i++)
        {
            Console.WriteLine("Iteration {0}", i);
            long sum = 0;
            Stopwatch sw = Stopwatch.StartNew();
            for (int j = 0; j < ks.Length; j++)
            {
                int k = ks[j];
                unsafe
                {
                    bool input = k > 9;
                    byte A = *((byte*)(&input)); // 1
                    sum += A * (k + 0x37) - (A - 1) * (k + 0x30);
                }
            }
            sw.Stop();
            Console.WriteLine("Unsafe code: {0}; {1}ms",
                              sum, sw.ElapsedMilliseconds);

            sum = 0;
            sw = Stopwatch.StartNew();
            for (int j = 0; j < ks.Length; j++)
            {
                int k = ks[j];
                sum += k > 9 ? k + 0x37 : k + 0x30;
            }
            sw.Stop();
            Console.WriteLine("Conditional: {0}; {1}ms",
                              sum, sw.ElapsedMilliseconds);
        }
    }
}

Note that on my computer this does give the same values for sum, but I'm not at all sure whether it's guaranteed to. I don't know that there's any guarantee of what the in-memory representation of true is... so on some CLRs you could potentially get the wrong answer.

However, I would point out that on my laptop, this loop of 100 million operations only takes around 300ms (and that's including adding to the sum and the initial array access, which may well be taking significant time, particularly due to cache misses)... are you really sure this is the bottleneck? How are you hoping to obtain data to hash so fast that this becomes the problem?

EDIT: I've just added another loop to see a "base case":

for (int j = 0; j < ks.Length; j++)
{
    int k = ks[j];
    sum += k + 0x30;
}

That takes about half the time... so only half the time is actually spent in the hash-specific code. Are you really, really sure this is a crucial bit of code to optimize at the cost of readability and potentially correctness?

Convert bool to byte in C#, Convert bool to byte in C#. ConvertDataTypes is the helpfull website for converting your data types in several programming languages. Viewed 394 times 0 After implementing the huffman algorithm in Scala, I'm now left with a array of bits with a length of over 10.000. Now I want to convert this array to bytes and write it to a file in the fastest way possible.

How about

byte x = Convert.ToByte(true);

Convert boolean to byte in Java, Convert boolean to byte in Java. ConvertDataTypes is the helpfull website for converting your data types in several programming languages. Simple question: considering that a bool (true, false) is the same as a bit (1, 0), what is the correct way to convert eight bools into a byte in C#?

// Warning! Brain-compiled code ahead!
static readonly char[] HexChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
public static string ToHex(this byte[] me)
{
    if ( me == null ) return null;
    int ml = me.Length;
    char[] c = new char[2*ml];

    int cp = 0;
    for (int i = 0; i < ml; i++ )
    {
        c[cp++] = HexChars[me[i]&15];
        c[cp++] = HexChars[me[i]>>4];
    }
    return new string(c);
}

BitConverter.ToBoolean Method (System), Tries to convert the string representation of a number to its Byte equivalent, and returns a value that public static bool TryParse (string s, out byte result); What is fastest way to convert bool to byte? I want this mapping: False=0, True=1. Note: I don't want to use any if statements or other conditional statements. I don't want the CPU to halt or guess next statement. Update: For those who want to see the point of this question. This example shows how two if statement are reduced from the code.

The following is a simple benchmark to compare the three options:

    Int32 j = 0;
    bool b = true;

    for (int n = 0; n < 5; n++) {
        Stopwatch sw1 = new Stopwatch();
        Stopwatch sw2 = new Stopwatch();
        Stopwatch sw3 = new Stopwatch();
        sw1.Start();
        for (int i = 100 * 1000 * 1000; i > 0; i--)
            unsafe { j = *(int*)(&b); }
        sw1.Stop();

        sw2.Start();
        for (int i = 100 * 1000 * 1000; i > 0; i--)
            j = b ? 1 : 0;
        sw2.Stop();

        sw3.Start();
        for (int i = 100 * 1000 * 1000; i > 0; i--)
            j = Convert.ToInt32(b);
        sw3.Stop();
        Trace.WriteLine("sw1: " + sw1.ElapsedMilliseconds +
            "  sw2:" + sw2.ElapsedMilliseconds + ", +" + 100 * (sw2.ElapsedMilliseconds - sw1.ElapsedMilliseconds) / sw1.ElapsedMilliseconds + "% relative to sw1" +
            "  sw3:" + sw3.ElapsedMilliseconds + ", +" + 100 * (sw3.ElapsedMilliseconds - sw1.ElapsedMilliseconds) / sw1.ElapsedMilliseconds + "% relative to sw1"
            );
    }

The results:

sw1: 172  sw2:218, +26% relative to sw1  sw3:213, +23% relative to sw1
sw1: 168  sw2:211, +25% relative to sw1  sw3:211, +25% relative to sw1
sw1: 167  sw2:212, +26% relative to sw1  sw3:208, +24% relative to sw1
sw1: 167  sw2:211, +26% relative to sw1  sw3:209, +25% relative to sw1
sw1: 167  sw2:212, +26% relative to sw1  sw3:210, +25% relative to sw1

Conclusion:

The unsafe method is about 25% faster than the other two!

The relative slowness of the "if" version is due to the high cost of branching. The cost of the Convert could have been avoided if Microsoft would do the conversion at compile time..

Byte.TryParse Method (System), We convert bools to ints, first running through an example. We then test unsafe code in converting bools to ints. We benchmark to ensure our method is fast.Bool. How they work. Suppose we have 8 bools b[0] to b[7] whose least significant bits are named a-h respectively that we want to pack into a single byte. Treating those 8 consecutive bools as one 64-bit word and load them we'll get the bits in reversed order in a little-endian machine.

C# Convert Bool to Int, Fastest way to pack an array of boolean values into bytes and zeros (eg 10011011), then convert that to a decimal value (eg 155), then pack that into a byte. ToBoolean(SByte) Converts the value of the specified 8-bit signed integer to an equivalent Boolean value. ToBoolean(String, IFormatProvider) Converts the specified string representation of a logical value to its Boolean equivalent, using the specified culture-specific formatting information.

Fastest way to pack an array of boolean values into bytes : PHP, Conversion from another variable type to BOOL:The result is TRUE when the operand is not equal to b := BYTE_TO_BOOL(2#11010101); (* Result is TRUE *) Fastest way to pack an array of boolean values into bytes I have a large array of boolean values that I'd like to store efficiently in a binary file. The way I have been doing this is to arrange them in groups of 8 booleans (eg T,F,F,T,T,F,T,T), make them into a a string of ones and zeros (eg 10011011), then convert that to a decimal value (eg

TO_BOOL-Converting - Beckhoff Information System, I know I could do it like for example "if(someBool == true) someInt = 1;" and reverse, but I would like to know if there is any way to convert it  So for my S7-416 I ended up creating some FCs in SCL and in SCL apparently there is a much better convert function. The word to int and dint is one line. I did the word to byte (high and low) by using thw word to byte function (gets the lower byte) and then shifting the word to the right to get the lower byte. I used a similar logic for the bits.

Comments
  • If x ? 1 : 0 is actually too slow for you, then you REALLY need to reexamine what you're trying to do. If a conversion at that level is happening tens of millions of times per second (the only way it'll ever noticeably affect performance), then why aren't you writing it in ASM or something anyway? That's the only way you're ever going to significantly beat x ? 1 : 0 for speed.
  • It's sort of funny that the conditional "needs to be optimized" when there is at least one (possible two) unnecessary multiplies in that ;-) (But at the end of the day ... it. just. doesn't. matter.) Another approach may be to use switch which can be optimized as a single jump -- not sure if C# or the JIT does it. Yet another approach is a LOOKUP TABLE. Whee! :)
  • @Amir: It's perfectly valid, and frequently useful, for others to point out that you're barking up the wrong tree. Nobody is trying to treat you unprofessionally; you have a lot of people who are trying to give you advice so that you can a) not waste your time on meaningless optimization, and b) use this site more productively. Many of us are surprised to see this question being asked, and that may come across in our comments. But if you read them from a non-defensive point of view, you'll find that no one has insulted you, only advised you on your problem. That's what Stack Overflow is for.
  • "One should be silent and learn" - downvoting seems to be another option.
  • @Amir: Usually the one who's supposed to be silent and learn is the one who asked for help. The rest of us try to give constructive information, and "don't do it this way" is constructive (and very helpful) if it's correct. If someone shows me a better way to do something, I don't care about making the old way work anymore.
  • This is the unsafe code Jon was talking about, and is the way to go. +1
  • And how does this fit into the byte-to-hex conversion?
  • @Henk Holterman: Not at all. Like the question ;) But it's an excellent answer.
  • While this is undoubtedly a clever solution, I'd crucify any developer that actually used this in production C# code without a lengthy explanation and proof as to how they came to the conclusion that if statements and byte conversions provide any measurable improvement in speed at the cost of violating least astonishment and maintenance.
  • @Jon - If your efforts manage to convince @Amir to switch his accepted answer you'll get no complaints from me, you may even get some light applause.