kzen.dev
  • Pertanyaan
  • Tag
  • Pengguna
Notifikasi
Imbalan
Registrasi
Setelah Anda mendaftar, Anda akan diberitahu tentang balasan dan komentar untuk pertanyaan Anda.
Gabung
Jika Anda sudah memiliki akun, masuk untuk memeriksa pemberitahuan baru.
Akan ada hadiah untuk pertanyaan, jawaban, dan komentar tambahan.
Lebih
Sumber
Sunting
 Brian
Brian
Question

Apakah ada konverter printf untuk mencetak dalam format biner?

Saya dapat mencetak dengan printf sebagai bilangan heksa atau oktal. Apakah ada tag format untuk mencetak sebagai biner, atau basis sembarang?

Saya menjalankan gcc.

printf("%d %x %o\n", 10, 10, 10); //prints "10 A 12\n"
print("%b\n", 10); // prints "%b\n"
400 2008-09-21T20:04:58+00:00 20
Valeriu
Valeriu 55188
Pertanyaan edit 26 November 2021 в 4:27
Pemrograman
c
printf
Popular videos
Section, Week 5
Section, Week 5
7 tahun yang lalu
String.Format / printf in VBA
String.Format / printf in VBA
3 tahun yang lalu
#01 || Output Function printf( ) || Format Specifiers || Programimi ne Gjuhen C || UPT.
#01 || Output Function printf( ) || Format Specifiers || Programimi ne Gjuhen C || UPT.
2 tahun yang lalu
String.Format / printf in VBA
String.Format / printf in VBA
3 tahun yang lalu
Print Sertifikat Kertas Concord di HP Pagewide Pro 477DW
Print Sertifikat Kertas Concord di HP Pagewide Pro 477DW
2 tahun yang lalu
Cara setting ukuran kertas continous form (1/2 letter) & kertas F4 di laptop
Cara setting ukuran kertas continous form (1/2 letter) & kertas F4 di laptop
1 tahun yang lalu
Document cannot be printed - Solved
Document cannot be printed - Solved
3 tahun yang lalu
#2 Pengenalan Pemrograman C dan Coding Dasarnya
#2 Pengenalan Pemrograman C dan Coding Dasarnya
2 tahun yang lalu
Cara Stop Printer Yang Mencetak Resi Terus Menerus
Cara Stop Printer Yang Mencetak Resi Terus Menerus
5 tahun yang lalu
CARA SETTING HALF LETTER ( NOTA INVOICE)
CARA SETTING HALF LETTER ( NOTA INVOICE)
3 tahun yang lalu
Penting !!! Cara mengetahui Printer yang aktif sebelum mencetak dokumen
Penting !!! Cara mengetahui Printer yang aktif sebelum mencetak dokumen
4 tahun yang lalu
Faktur dengan PrintDocument di Vb.Net
Faktur dengan PrintDocument di Vb.Net
1 tahun yang lalu
CARA AMBIL DATA ABSEN FINGER PRINT DENGAN FLASHDISK DAN PINDAHKAN KE KOMPUTER
CARA AMBIL DATA ABSEN FINGER PRINT DENGAN FLASHDISK DAN PINDAHKAN KE KOMPUTER
2 tahun yang lalu
How to Configure JustPrint V2R2 for Marker & Pattern Printing
How to Configure JustPrint V2R2 for Marker & Pattern Printing
5 tahun yang lalu
hasil print tidak sesuai dengan print preview
hasil print tidak sesuai dengan print preview
3 tahun yang lalu
« Sebelumnya
Selanjutnya »
Pertanyaan ini memiliki :value jawaban dalam bahasa Inggris, untuk membacanya masuk ke akun Anda.
William Whyte
William Whyte
8 Juli 2010 в 10:07
2010-07-08T22:07:56+00:00
Lebih
Sumber
Sunting
#8491835

Hacky tapi bekerja untuk saya.

#define BYTE_TO_BINARY_PATTERN "%c%c%c%c%c%c%c%c"
#define BYTE_TO_BINARY(byte)  \
  (byte & 0x80 ? '1' : '0'), \
  (byte & 0x40 ? '1' : '0'), \
  (byte & 0x20 ? '1' : '0'), \
  (byte & 0x10 ? '1' : '0'), \
  (byte & 0x08 ? '1' : '0'), \
  (byte & 0x04 ? '1' : '0'), \
  (byte & 0x02 ? '1' : '0'), \
  (byte & 0x01 ? '1' : '0') 
printf("Leading text "BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(byte));

Untuk tipe multi-byte

printf("m: "BYTE_TO_BINARY_PATTERN" "BYTE_TO_BINARY_PATTERN"\n",
  BYTE_TO_BINARY(m>>8), BYTE_TO_BINARY(m));

Sayangnya kau butuh semua kutipan tambahan. Pendekatan ini memiliki risiko efisiensi dari makro (jangan lulus sebuah fungsi sebagai argumen ke `BYTE_Tapi menghindari masalah memori dan beberapa undangan strcat dalam beberapa proposal lain di sini.

Valeriu
Valeriu 55188
Jawaban edit 26 November 2021 в 4:28
243
0
Pengguna anonim
20 Oktober 2010 в 1:37
2010-10-20T01:37:58+00:00
Lebih
Sumber
Sunting
#8491837

Cetak Binari untuk Setiap Datatype

//assumes little endian
void printBits(size_t const size, void const * const ptr)
{
    unsigned char *b = (unsigned char*) ptr;
    unsigned char byte;
    int i, j;

    for (i=size-1;i>=0;i--)
    {
        for (j=7;j>=0;j--)
        {
            byte = (b[i] >> j) & 1;
            printf("%u", byte);
        }
    }
    puts("");
}

uji

int main(int argv, char* argc[])
{
        int i = 23;
        uint ui = UINT_MAX;
        float f = 23.45f;
        printBits(sizeof(i), &i);
        printBits(sizeof(ui), &ui);
        printBits(sizeof(f), &f);
        return 0;
}
Valeriu
Valeriu 55188
Jawaban edit 26 November 2021 в 4:28
196
0
 EvilTeach
EvilTeach
22 September 2008 в 2:59
2008-09-22T02:59:20+00:00
Lebih
Sumber
Sunting
#8491829

Berikut adalah hack cepat untuk menunjukkan teknik untuk melakukan apa yang Anda inginkan.

#include <stdio.h>      /* printf */
#include <string.h>     /* strcat */
#include <stdlib.h>     /* strtol */

const char *byte_to_binary(int x)
{
    static char b[9];
    b[0] = '\0';

    int z;
    for (z = 128; z > 0; z >>= 1)
    {
        strcat(b, ((x & z) == z) ? "1" : "0");
    }

    return b;
}

int main(void)
{
    {
        /* binary string to int */

        char *tmp;
        char *b = "0101";

        printf("%d\n", strtol(b, &tmp, 2));
    }

    {
        /* byte to binary string */

        printf("%s\n", byte_to_binary(5));
    }

    return 0;
}
Valeriu
Valeriu 55188
Jawaban edit 26 November 2021 в 4:28
150
0
 DGentry
DGentry
22 September 2008 в 2:53
2008-09-22T02:53:38+00:00
Lebih
Sumber
Sunting
#8491828

There isn't a binary conversion specifier in glibc normally.

It is possible to add custom conversion types to the printf() family of functions in glibc. See register_printf_function for details. You could add a custom %b conversion for your own use, if it simplifies the application code to have it available.

Here is an example of how to implement a custom printf formats in glibc.

82
0
 Shahbaz
Shahbaz
10 November 2013 в 1:05
2013-11-10T01:05:33+00:00
Lebih
Sumber
Sunting
#8491854

You could use a small table to improve speed1. Similar techniques are useful in the embedded world, for example, to invert a byte:

const char *bit_rep[16] = {
    [ 0] = "0000", [ 1] = "0001", [ 2] = "0010", [ 3] = "0011",
    [ 4] = "0100", [ 5] = "0101", [ 6] = "0110", [ 7] = "0111",
    [ 8] = "1000", [ 9] = "1001", [10] = "1010", [11] = "1011",
    [12] = "1100", [13] = "1101", [14] = "1110", [15] = "1111",
};

void print_byte(uint8_t byte)
{
    printf("%s%s", bit_rep[byte >> 4], bit_rep[byte & 0x0F]);
}

1 I'm mostly referring to embedded applications where optimizers are not so aggressive and the speed difference is visible.

Peter Mortensen
Peter Mortensen
Jawaban edit 25 Desember 2017 в 9:16
40
0
 danijar
danijar
23 Desember 2014 в 7:46
2014-12-23T19:46:01+00:00
Lebih
Sumber
Sunting
#8491861

Print the least significant bit and shift it out on the right. Doing this until the integer becomes zero prints the binary representation without leading zeros but in reversed order. Using recursion, the order can be corrected quite easily.

#include <stdio.h>

void print_binary(int number)
{
    if (number) {
        print_binary(number >> 1);
        putc((number & 1) ? '1' : '0', stdout);
    }
}

To me, this is one of the cleanest solutions to the problem. If you like 0b prefix and a trailing new line character, I suggest wrapping the function.

Online demo

GRg6bQ - Online C Compiler & Debugging Tool - Ideone.com
Compile various programming languages online. Add input stream, save output, add notes and tags.
ideone.com
21
0
 ideasman42
ideasman42
3 Agustus 2014 в 7:46
2014-08-03T19:46:28+00:00
Lebih
Sumber
Sunting
#8491857

Based on @William Whyte's answer, this is a macro that provides int8,16,32 & 64 versions, reusing the INT8 macro to avoid repetition.

/* --- PRINTF_BYTE_TO_BINARY macro's --- */
#define PRINTF_BINARY_PATTERN_INT8 "%c%c%c%c%c%c%c%c"
#define PRINTF_BYTE_TO_BINARY_INT8(i)    \
    (((i) & 0x80ll) ? '1' : '0'), \
    (((i) & 0x40ll) ? '1' : '0'), \
    (((i) & 0x20ll) ? '1' : '0'), \
    (((i) & 0x10ll) ? '1' : '0'), \
    (((i) & 0x08ll) ? '1' : '0'), \
    (((i) & 0x04ll) ? '1' : '0'), \
    (((i) & 0x02ll) ? '1' : '0'), \
    (((i) & 0x01ll) ? '1' : '0')

#define PRINTF_BINARY_PATTERN_INT16 \
    PRINTF_BINARY_PATTERN_INT8              PRINTF_BINARY_PATTERN_INT8
#define PRINTF_BYTE_TO_BINARY_INT16(i) \
    PRINTF_BYTE_TO_BINARY_INT8((i) >> 8),   PRINTF_BYTE_TO_BINARY_INT8(i)
#define PRINTF_BINARY_PATTERN_INT32 \
    PRINTF_BINARY_PATTERN_INT16             PRINTF_BINARY_PATTERN_INT16
#define PRINTF_BYTE_TO_BINARY_INT32(i) \
    PRINTF_BYTE_TO_BINARY_INT16((i) >> 16), PRINTF_BYTE_TO_BINARY_INT16(i)
#define PRINTF_BINARY_PATTERN_INT64    \
    PRINTF_BINARY_PATTERN_INT32             PRINTF_BINARY_PATTERN_INT32
#define PRINTF_BYTE_TO_BINARY_INT64(i) \
    PRINTF_BYTE_TO_BINARY_INT32((i) >> 32), PRINTF_BYTE_TO_BINARY_INT32(i)
/* --- end macros --- */

#include <stdio.h>
int main() {
    long long int flag = 1648646756487983144ll;
    printf("My Flag "
           PRINTF_BINARY_PATTERN_INT64 "\n",
           PRINTF_BYTE_TO_BINARY_INT64(flag));
    return 0;
}

This outputs:

My Flag 0001011011100001001010110111110101111000100100001111000000101000

For readability you may want to add a separator for eg:

My Flag 00010110,11100001,00101011,01111101,01111000,10010000,11110000,00101000
19
0
 R..
R..
29 Januari 2011 в 9:34
2011-01-29T21:34:05+00:00
Lebih
Sumber
Sunting
#8491841

Here's a version of the function that does not suffer from reentrancy issues or limits on the size/type of the argument:

#define FMT_BUF_SIZE (CHAR_BIT*sizeof(uintmax_t)+1)
char *binary_fmt(uintmax_t x, char buf[static FMT_BUF_SIZE])
{
    char *s = buf + FMT_BUF_SIZE;
    *--s = 0;
    if (!x) *--s = '0';
    for(; x; x/=2) *--s = '0' + x%2;
    return s;
}

Note that this code would work just as well for any base between 2 and 10 if you just replace the 2's by the desired base. Usage is:

char tmp[FMT_BUF_SIZE];
printf("%s\n", binary_fmt(x, tmp));

Where x is any integral expression.

16
0
Pengguna anonim
18 Maret 2009 в 6:57
2009-03-18T06:57:47+00:00
Lebih
Sumber
Sunting
#8491831
const char* byte_to_binary( int x )
{
    static char b[sizeof(int)*8+1] = {0};
    int y;
    long long z;
    for (z=1LL<<sizeof(int)*8-1,y=0; z>0; z>>=1,y++)
    {
        b[y] = ( ((x & z) == z) ? '1' : '0');
    }

    b[y] = 0;

    return b;
}
12
0
 TechplexEngineer
TechplexEngineer
15 Februari 2012 в 3:39
2012-02-15T03:39:20+00:00
Lebih
Sumber
Sunting
#8491849

None of the previously posted answers are exactly what I was looking for, so I wrote one. It is super simple to use %B with the printf!

    /*
     * File:   main.c
     * Author: Techplex.Engineer
     *
     * Created on February 14, 2012, 9:16 PM
     */

    #include <stdio.h>
    #include <stdlib.h>
    #include <printf.h>
    #include <math.h>
    #include <string.h>

    static int printf_arginfo_M(const struct printf_info *info, size_t n, int *argtypes) {
        /* "%M" always takes one argument, a pointer to uint8_t[6]. */
        if (n > 0) {
            argtypes[0] = PA_POINTER;
        }
        return 1;
    } /* printf_arginfo_M */

    static int printf_output_M(FILE *stream, const struct printf_info *info, const void *const *args) {
        int value = 0;
        int len;

        value = *(int **) (args[0]);

        //Beginning of my code ------------------------------------------------------------
        char buffer [50] = ""; //Is this bad?
        char buffer2 [50] = ""; //Is this bad?
        int bits = info->width;
        if (bits <= 0)
            bits = 8; // Default to 8 bits

        int mask = pow(2, bits - 1);
        while (mask > 0) {
            sprintf(buffer, "%s", (((value & mask) > 0) ? "1" : "0"));
            strcat(buffer2, buffer);
            mask >>= 1;
        }
        strcat(buffer2, "\n");
        // End of my code --------------------------------------------------------------
        len = fprintf(stream, "%s", buffer2);
        return len;
    } /* printf_output_M */

    int main(int argc, char** argv) {

        register_printf_specifier('B', printf_output_M, printf_arginfo_M);

        printf("%4B\n", 65);

        return (EXIT_SUCCESS);
    }
9
0
 rlerallut
rlerallut
21 September 2008 в 8:11
2008-09-21T20:11:16+00:00
Lebih
Sumber
Sunting
#8491826

Beberapa runtime mendukung "%b" meskipun itu bukan standar.

Juga lihat di sini untuk diskusi yang menarik:

http://bytes.com/forum/thread591027.html

HTH

conversion to binary in printf() - C / C++
conversion to binary in printf(). C / C++ Forums on Bytes.
bytes.com
8
0
chux  - Reinstate Monica
chux - Reinstate Monica
6 Januari 2016 в 7:57
2016-01-06T19:57:42+00:00
Lebih
Sumber
Sunting
#8491864

Is there a printf converter to print in binary format?

The printf() family is only able to print in base 8, 10, and 16 using the standard specifiers directly. I suggest creating a function that converts the number to a string per code's particular needs.


To print in any base [2-36]

All other answers so far have at least one of these limitations.

  1. Use static memory for the return buffer. This limits the number of times the function may be used as an argument to printf().

  2. Allocate memory requiring the calling code to free pointers.

  3. Require the calling code to explicitly provide a suitable buffer.

  4. Call printf() directly. This obliges a new function for to fprintf(), sprintf(), vsprintf(), etc.

  5. Use a reduced integer range.

The following has none of the above limitation. It does require C99 or later and use of "%s". It uses a compound literal to provide the buffer space. It has no trouble with multiple calls in a printf().

#include <assert.h>
#include <limits.h>
#define TO_BASE_N (sizeof(unsigned)*CHAR_BIT + 1)

//                               v. compound literal .v
#define TO_BASE(x, b) my_to_base((char [TO_BASE_N]){""}, (x), (b))

// Tailor the details of the conversion function as needed
// This one does not display unneeded leading zeros
// Use return value, not `buf`
char *my_to_base(char *buf, unsigned i, int base) {
  assert(base >= 2 && base <= 36);
  char *s = &buf[TO_BASE_N - 1];
  *s = '\0';
  do {
    s--;
    *s = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"[i % base];
    i /= base;
  } while (i);

  // Could employ memmove here to move the used buffer to the beginning

  return s;
}

#include <stdio.h>
int main(void) {
  int ip1 = 0x01020304;
  int ip2 = 0x05060708;
  printf("%s %s\n", TO_BASE(ip1, 16), TO_BASE(ip2, 16));
  printf("%s %s\n", TO_BASE(ip1, 2), TO_BASE(ip2, 2));
  puts(TO_BASE(ip1, 8));
  puts(TO_BASE(ip1, 36));
  return 0;
}

Output

1020304 5060708
1000000100000001100000100 101000001100000011100001000
100401404
A2F44
chux  - Reinstate Monica
chux - Reinstate Monica
Jawaban edit 15 November 2018 в 2:10
Compound literals - cppreference.com
en.cppreference.com
7
0
 mrwes
mrwes
3 Juli 2009 в 8:45
2009-07-03T08:45:42+00:00
Lebih
Sumber
Sunting
#8491834

This code should handle your needs up to 64 bits. I created 2 functions pBin & pBinFill. Both do the same thing, but pBinFill fills in the leading spaces with the fillChar. The test function generates some test data, then prints it out using the function.


char pBinFill(long int x,char so, char fillChar); // version with fill char pBin(long int x, char so); // version without fill #define kDisplayWidth 64

char pBin(long int x,char so) { char s[kDisplayWidth+1]; int i=kDisplayWidth; s[i--]=0x00; // terminate string do { // fill in array from right to left s[i--]=(x & 1) ? '1':'0'; // determine bit x>>=1; // shift right 1 bit } while( x &gt 0); i++; // point to last valid character sprintf(so,"%s",s+i); // stick it in the temp string string return so; }


char* pBinFill(long int x,char *so, char fillChar)
{ // fill in array from right to left
 char s[kDisplayWidth+1];
 int  i=kDisplayWidth;
 s[i--]=0x00;   // terminate string
 do
 { // fill in array from right to left
  s[i--]=(x & 1) ? '1':'0';
  x>>=1;  // shift right 1 bit
 } while( x > 0);
 while(i>=0) s[i--]=fillChar;    // fill with fillChar 
 sprintf(so,"%s",s);
 return so;
}

void test()
{
 char so[kDisplayWidth+1]; // working buffer for pBin
 long int val=1;
 do
 {
   printf("%ld =\t\t%#lx =\t\t0b%s\n",val,val,pBinFill(val,so,'0'));
   val*=11; // generate test data
 } while (val < 100000000);
}

Output: 00000001 = 0x000001 = 0b00000000000000000000000000000001 00000011 = 0x00000b = 0b00000000000000000000000000001011 00000121 = 0x000079 = 0b00000000000000000000000001111001 00001331 = 0x000533 = 0b00000000000000000000010100110011 00014641 = 0x003931 = 0b00000000000000000011100100110001 00161051 = 0x02751b = 0b00000000000000100111010100011011 01771561 = 0x1b0829 = 0b00000000000110110000100000101001 19487171 = 0x12959c3 = 0b00000001001010010101100111000011

7
0
 quinmars
quinmars
22 September 2008 в 8:25
2008-09-22T08:25:57+00:00
Lebih
Sumber
Sunting
#8491830

Maybe a bit OT, but if you need this only for debuging to understand or retrace some binary operations you are doing, you might take a look on wcalc (a simple console calculator). With the -b options you get binary output.

e.g.

$ wcalc -b "(256 | 3) & 0xff"
 = 0b11
6
0
Florian B&#246;sch
Florian Bösch
21 September 2008 в 8:09
2008-09-21T20:09:35+00:00
Lebih
Sumber
Sunting
#8491825

Tidak ada fungsi pemformatan dalam pustaka standar C untuk mengeluarkan biner seperti itu. Semua operasi format yang didukung keluarga printf adalah untuk teks yang dapat dibaca manusia.

6
0
 kapil
kapil
1 Maret 2015 в 5:48
2015-03-01T17:48:35+00:00
Lebih
Sumber
Sunting
#8491862

The following recursive function might be useful:

void bin(int n)
{
    /* Step 1 */
    if (n > 1)
        bin(n/2);
    /* Step 2 */
    printf("%d", n % 2);
}
Peter Mortensen
Peter Mortensen
Jawaban edit 25 Desember 2017 в 9:16
5
0
малин чекуров
малин чекуров
12 Mei 2018 в 8:51
2018-05-12T20:51:34+00:00
Lebih
Sumber
Sunting
#8491875
void
print_binary(unsigned int n)
{
    unsigned int mask = 0;
    /* this grotesque hack creates a bit pattern 1000... */
    /* regardless of the size of an unsigned int */
    mask = ~mask ^ (~mask >> 1);

    for(; mask != 0; mask >>= 1) {
        putchar((n & mask) ? '1' : '0');
    }

}
4
0
 paniq
paniq
17 Juli 2011 в 1:19
2011-07-17T13:19:49+00:00
Lebih
Sumber
Sunting
#8491844

I optimized the top solution for size and C++-ness, and got to this solution:

inline std::string format_binary(unsigned int x)
{
    static char b[33];
    b[32] = '\0';

    for (int z = 0; z < 32; z++) {
        b[31-z] = ((x>>z) & 0x1) ? '1' : '0';
    }

    return b;
}
4
0
 wnoise
wnoise
21 September 2008 в 8:45
2008-09-21T20:45:42+00:00
Lebih
Sumber
Sunting
#8491827

Tidak ada cara standar dan portabel.

Beberapa implementasi menyediakan itoa(), tetapi tidak akan ada di sebagian besar, dan memiliki antarmuka yang agak payah. Tetapi kodenya ada di belakang tautan dan seharusnya memungkinkan Anda mengimplementasikan formatter Anda sendiri dengan cukup mudah.

C Programming/stdlib.h/itoa - Wikibooks, open books for an open world
en.wikibooks.org
3
0
 eMPee584
eMPee584
21 Agustus 2011 в 9:45
2011-08-21T09:45:38+00:00
Lebih
Sumber
Sunting
#8491846

I liked the code by paniq, the static buffer is a good idea. However it fails if you want multiple binary formats in a single printf() because it always returns the same pointer and overwrites the array.

Here's a C style drop-in that rotates pointer on a split buffer.

char *
format_binary(unsigned int x)
{
    #define MAXLEN 8 // width of output format
    #define MAXCNT 4 // count per printf statement
    static char fmtbuf[(MAXLEN+1)*MAXCNT];
    static int count = 0;
    char *b;
    count = count % MAXCNT + 1;
    b = &fmtbuf[(MAXLEN+1)*count];
    b[MAXLEN] = '\0';
    for (int z = 0; z < MAXLEN; z++) { b[MAXLEN-1-z] = ((x>>z) & 0x1) ? '1' : '0'; }
    return b;
}
3
0
Tambahkan pertanyaan
Kategori
Semua
Teknologi
Budaya / Rekreasi
Kehidupan / Seni
Ilmu Pengetahuan
Profesional
Bisnis
Pengguna
Semua
Baru
Populer
1
Роман Азаров
Terdaftar 2 hari yang lalu
2
Mansur Zakirov
Terdaftar 5 hari yang lalu
3
Тагир Мамедов
Terdaftar 1 minggu yang lalu
4
Алексей Толманов
Terdaftar 1 minggu yang lalu
5
Valeriu Vodnicear
Terdaftar 2 minggu yang lalu
BG
DE
EL
ES
FR
ID
IT
JA
LT
NL
PT
RU
SK
TR
ZH
© kzen.dev 2023
Sumber
stackoverflow.com
di bawah lisensi cc by-sa 3.0 dengan atribusi