Use Integer#toBinaryString():

byte b1 = (byte) 129;
String s1 = String.format("%8s", Integer.toBinaryString(b1 & 0xFF)).replace(' ', '0');
System.out.println(s1); // 10000001

byte b2 = (byte) 2;
String s2 = String.format("%8s", Integer.toBinaryString(b2 & 0xFF)).replace(' ', '0');
System.out.println(s2); // 00000010

DEMO.

Answer from João Silva on Stack Overflow
🌐
Mkyong
mkyong.com › home › java › java – how to convert a byte to a binary string
Java - How to convert a byte to a binary string - Mkyong.com
June 3, 2020 - In Java, we can use Integer.toBinaryString(int) to convert a byte to a binary string representative.
Discussions

c - Bytes to binary conversion function - Code Review Stack Exchange
I created a quick function to convert n bytes into binary for my student. She is not on that level yet, but I think it would be best for her if my demonstrative functions aren't trash. void binary ... More on codereview.stackexchange.com
🌐 codereview.stackexchange.com
file - python how to convert bytes to binary - Stack Overflow
I'm trying to read a file's contents and convert them into what is actually stored in memory if I write file = open("filename","br") binary = "0b" for i in file.read()... More on stackoverflow.com
🌐 stackoverflow.com
From Byte to Binary conversion [SOLVED]
Hello guys, I would like to convert a value from 'INT' (0 to 255) in binary (0000000 to 1111111) and then print it on the serial port to view it. Seccessivamente would like to read and write every single bit and make comparisons with the IF function More on forum.arduino.cc
🌐 forum.arduino.cc
8
0
October 20, 2015
How can I convert bytes object to decimal or binary representation in python? - Stack Overflow
I wanted to convert an object of type bytes to binary representation in python 3.x. For example, I want to convert the bytes object b'\x11' to the binary representation 00010001 in binary (or 17 in More on stackoverflow.com
🌐 stackoverflow.com
🌐
CheckYourMath
checkyourmath.com › convert › digital_storage › bytes_bits.php
Convert Bytes to bits - Digital Storage Conversions (Binary)
A bit is a unit used to measure digital storage and is based on "Binary multiples of bits". The symbol for bit is b. There are 8 bits in a Byte. Let's take a closer look at the conversion formula so that you can do these conversions yourself with a calculator or with an old-fashioned pencil and paper. ... Next, let's look at an example showing the work and calculations that are involved in converting from Bytes to bits (B to b).
Top answer
1 of 4
8

It's not terrible as it stands, but I think there are some ways it might be improved.

Include all needed files

The function needs several #include files that are not listed. Specifically, it needs these:

#include <stddef.h>
#include <stdio.h>
#include <limits.h>

It's important to list those, especially for a beginner.

Be careful with signed and unsigned

In the binary function, the compares an int iByte to a size_t nBytes, but size_t is unsigned and int is signed. Instead, declare both variables as size_t types, or better, see the next suggestion.

Count down instead of up

If we count down instead of up, not only do many compilers generate more efficient code, but we also avoid the signed/unsigned problem mentioned above.

Declare variables in as small a scope as practical

Putting all definitions at the top of the function is an antique style of C. In modern C (C99 and later) we declare variables as late as practical, ideally as they are defined, to avoid problems of uninitialized variables.

Use a bitmask directly instead of calculating

I would write the inner loop like this:

for(unsigned char mask = 1U << (CHAR_BIT-1); mask; mask >>= 1) 

That makes it very clear that we're using a bitmask and how it is calculated and handled.

Use a convenience cast

Rather than casting p every time, I'd be inclined to declare an internal unsigned char * variable and use that instead.

Avoid encoding types in names

C is a statically typed language, so it is neither necessary nor desirable to encode the type within the name. See NL.5 for more. (Those are C++ guidelines, but this is equally applicable to C.)

Use pointers

Sooner or later, even beginners are going to need to learn how to use pointers. They have the considerable advantage here in simplifying the code.

Use const where practical

The function does not and should not modify the pointed-to value, so it's better to make that explicit and declare it const.

Consider separating the function into two

One way to think of this code is that it's printing one or more bytes with additional separators and formatting. That suggests an alternative which is to separate out the part that just prints the ones and zeroes from the loop.

Results

Here's the slightly refactored code using all of the suggestions above:

#include <stddef.h>
#include <stdio.h>
#include <limits.h>

void toBinary(const unsigned char *ptr) {
    for(unsigned char mask = 1U << (CHAR_BIT-1); mask; mask >>= 1) {
        putchar(*ptr & mask ? '1' : '0');
    }
}

void binary(const void* p, size_t nBytes) {
    for(const unsigned char* ptr = p; nBytes; --nBytes) {
        putchar('[');
        toBinary(ptr++);
        putchar(']');
        if(nBytes > 1) {
            putchar('\t');
        }
    }
    putchar('\n');
}

#define BINARY(x) binary(&x, sizeof x)

int main(void) {
    char a = 85;
    int b = 0x12345678;
    BINARY(a);
    BINARY(b);
}
2 of 4
6

Interface

I find it helps if we use verbs for function names. Instead of saying, "Here's some memory, let's binary() it," it's more natural to say, "Here's some memory, let's print() it." Now obviously print is much too general a name in C that has no overloading or namespaces, so we'd have to qualify: print_as_binary().

Since we don't plan to modify the pointed-to variable, we should accept p as a pointer to const void.

size_t is absolutely the right choice for a count variable such as nBytes.

Implementation

We don't need to create iBit and iByte up-front like that in modern C. We can give them smaller scope by declaring them within their respective for initialisations.

iByte really ought to match the type of nBytes - comparing signed and unsigned types is tricky, and we need to have at least the same range as what's passed to the function. The type of iBit doesn't matter, as we know that CHAR_BIT will be well within its range, regardless.

for (size_t iByte = 0;  iByte < nBytes;  iByte++)

When choosing the character to print, we could take advantage of the fact that C guarantees that 0 and 1 will have consecutive character codes:

putchar('0' + (bit & 1));

It's probably easier to print the separator string before the data, as that makes for a simpler test (iByte != 0).

We might want to assign p to an unsigned char* variable rather than explicitly casting it in the loop.

It's very surprising to see binary numbers written backwards like that. The standard convention in mathematics and programming is to write the most-significant bit first.

The macro

It's good practice to wrap all expansions of macro arguments within parentheses, so that if we are passed an expression, it is treated as a single unit:

#define BINARY(x) binary(&(x), sizeof (x))

Modified code:

#include <limits.h>
#include <stdint.h>
#include <stdio.h>

void print_as_binary(const void *p, size_t nBytes)
{
    const unsigned char *const q = p;

    putchar('[');
    for (size_t iByte = 0;  iByte < nBytes;  ++iByte) {
        if (iByte) {
            fputs("]\t[", stdout);
        }
        for (int iBit = CHAR_BIT;  iBit > 0;  --iBit) {
            int bit = q[iByte] >> (iBit - 1);
            putchar('0' + (bit & 1));
        }
    }

    printf("]\n");
}

#define PRINT_AS_BINARY(x) print_as_binary(&(x), sizeof (x))

int main(void)
{
    int t = 1000000;
    PRINT_AS_BINARY(t);
}
🌐
GeeksforGeeks
geeksforgeeks.org › python › convert-bytes-to-bits-in-python
Convert Bytes To Bits in Python - GeeksforGeeks
July 23, 2025 - This method counts the number of 1 bits in each byte of the byte sequence by converting each byte to its binary form and counting the occurrences of 1 using a generator expression and bin(byte).count('1').
🌐
GB to KB Conversion
gbmb.org › home › bytes conversion
Bytes to Bits Conversion
1 byte consists of 8 bits, which go together as one unit in storage, processing or transmission of digital information. Byte is the unit of data Unit symbol of byte is B (uppercase) 1 byte = 8 bits · Bit (b) is a measurement unit used in binary system to store or transmit data, like internet ...
Find elsewhere
🌐
Inch Calculator
inchcalculator.com › home › conversion › data storage › bytes › bytes to bits
Bytes to Bits Converter (B to b) - Inch Calculator
May 9, 2025 - For example, here's how to convert 5 bytes to bits using the formula above. ... There are 8 bits in a byte, which is why we use this value in the formula above. ... Bytes and bits are both units used to measure data storage. Keep reading to learn more about each unit of measure. A byte is a group of eight binary digits or bits.
🌐
GIGACalculator.com
gigacalculator.com › converters › data › bytes to bits converter
Bytes to Bits Converter - Convert Bytes to Bits
This is the basis for the ASCII ... to 01100001 in the ASCII table. To convert from bytes to bits you only need to multiply by 8....
🌐
Finxter
blog.finxter.com › home › learn python blog › 5 best ways to convert python bytes to binary string
5 Best Ways to Convert Python Bytes to Binary String - Be on the Right Side of Change
February 23, 2024 - The bin() function converts each byte to a binary string, which needs slicing to remove the ‘0b’ prefix, and then zfill() is used to pad the binary string with leading zeros.
🌐
Best Microcontroller Projects
best-microcontroller-projects.com › bit-byte.html
Bit byte conversion - How to change bits into bytes and back.
Here's an example: If you think of the number 174. 174 / 128= 1.359 : whole part 1- Subtract 127 from 174 leaving 46 ... So the binary number is 10101110 : you have converted the binary number from a bit into a byte using 16 calculations!
🌐
Kyle's Converter
kylesconverter.com › kyle's converter › data storage › bytes › bytes to megabytes (binary)
Convert Bytes to Megabytes (binary)
Converts from Bytes for you! Instantly Converts Bytes to Megabytes (binary) and Many More Data Storage Conversions Online. Bytes Conversion Charts. Many Other Conversions.
🌐
CheckYourMath
checkyourmath.com › convert › digital_storage › bits_bytes.php
Convert bits to Bytes - Digital Storage Conversions (Binary)
A Byte is a unit used to measure digital storage and is based on "Binary multiples of Bytes". The symbol for Byte is B. There are 0.125 Bytes in a bit. Let's take a closer look at the conversion formula so that you can do these conversions yourself with a calculator or with an old-fashioned pencil and paper. ... Next, let's look at an example showing the work and calculations that are involved in converting from bits to Bytes (b to B).
🌐
XConvert
xconvert.com › home › unit converter › digital storage › bytes to bits
Convert Bytes to Bits | XConvert
Practical tip: when converting Bytes to bits, just multiply by 8; when converting bits to Bytes, divide by 8. There are two systems for measuring digital data. The decimal (SI) system uses powers of 1000 (KB, MB, GB), while the binary (IEC) system uses powers of 1024 (KiB, MiB, GiB).
🌐
Binary Convert
binaryconvert.com
Online Binary-Decimal Converter
Online binary converter. Supports all types of variables, including single and double precision IEEE754 numbers
🌐
GIGACalculator.com
gigacalculator.com › converters › data › bits to bytes converter
Bits to Bytes Converter - Convert Bits to Bytes
There were attempts to use 10-bit "bytes", but they did not receive adoption. Both the bit and the byte are data units used for measuring data storage capacity and transmission capacity (bandwidth). The only difference between the two is that a byte is 8 times larger than a bit. A bit is the smallest possible amount of data in a binary ...
🌐
Arduino Forum
forum.arduino.cc › projects › programming
From Byte to Binary conversion [SOLVED] - Programming - Arduino Forum
October 20, 2015 - Hello guys, I would like to convert a value from 'INT' (0 to 255) in binary (0000000 to 1111111) and then print it on the serial port to view it. Seccessivamente would like to read and write every single bit and make comparisons with the IF function
🌐
Online String Tools
onlinestringtools.com › convert-string-to-bytes
Convert a String to Bytes – Online String Tools
This browser-based program converts a string to a byte array. The string is split into individual characters and then for each character, the program finds its byte representation, and prints it in the output area in the hexadecimal base. If you need bytes in bit form, use our string to binary bits ...