簡體   English   中英

將int轉換為一定大小的二進制字符串

[英]Convert int to binary string of certain size

用Java編程一段時間后,我一直在努力適應C,我需要幫助。 我正在尋找一種需要以下輸入的方法:

  1. 整數n ,要轉換為二進制字符串(字符數組)的整數。
  2. Integer length ,它定義字符串的長度(將從左側開始的未填充二進制數字的位置設置為默認值0)。

     //Here's some quick code in Java to get a better understanding of what I'm looking for: public static String convertToBinary(int length, int n) { return String.format("%1$" + bit + "s", Integer.toBinaryString(value)).replace(' ', '0'); } System.out.println(convertToBinary(8,1)); // OUTPUT: 00000001 (not just 1 or 01) 

有什么暗示與C語言等效嗎? 另外,您能否提供一個示例,說明如何返回結果二進制字符串?

(不是重復的,因為我要查找的是“ 00000001”,而不僅僅是“ 1”)

C標准庫不包含Integer.toBinaryString()的等效函數。 好消息是,編寫這樣的函數不會太復雜,並且,如果您正在學習C,那么此問題對於學習如何使用按位運算符來說是非常理想的。

您將需要查閱現有的教程或手冊以獲取所有詳細信息,但是這里有一些示例示例,這些示例對於此任務或類似任務很有用。 在這些示例中,所有數字均為無符號整數。

n >> m移中的所有位在n右移m步驟,以及在左側的零填充。 因此,如果n = 13 (1101 in binary) ,則n >> 1將為6 (ie 110) ,而n >> 2將為3 (ie 11)

n << m做同樣的事情,但是向左移動。 3 << 2 == 12 這等效於將n乘以2乘以m的冪。 (如果不清楚為什么會這樣,那么您需要考慮一下如何在一段時間內表示二進制數字,直到您清楚地理解它為止;如果您對該屬性有直觀的了解,它將使事情變得更加容易。)

n & m求一個數字,使得當且僅當n和meg 均為 1時,結果的每個位才為1 12 & 5 == 4 ,(1100、0101和0100分別表示為12、5和4)。

因此,將它們放在一起,當且僅當設置了位i時, n & (1 << i)才會為非零: 1顯然僅設置了一個位, 1 << i將其移動到適當的位置,並且n & (1 << i)檢查該位置是否也有n的1位。 (請記住,最右/最低有效位是位0 ,而不是位1。)因此,使用此方法很簡單,只需單獨檢查每個位以查看其是1還是0,就可以使用二進制轉換功能。

像這樣:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>

char *convertToBinary(int length, int n) {
    unsigned num = (unsigned)n;
    int n_bit = CHAR_BIT * sizeof(num);
    if(length > n_bit){
        fprintf(stderr, "specified length  greater than maximum length.\n");
        length = n_bit;//or expand size?
    }

    char *bin = malloc(n_bit + 1);//static char bin[CHAR_BIT * sizeof(num)+1]; If you change, memmove(-->return p;), free is not necessary.
    memset(bin, '0', n_bit);
    bin[n_bit] = 0;

    char *p = bin + n_bit;
    do {
        *--p = "01"[num & 1];
        num >>= 1;
    }while(num);

    int bits = bin + n_bit - p;
    if(bits < length){
        p -= length - bits;
        return memmove(bin, p, length + 1);
    } else if(bits > length){
        fprintf(stderr, "Specified length is not enough.(%s but length is %d)\n", p, length);
        return memmove(bin, p, bits+1);//or cut off
/*
        free(bin);
        return ""; or return NULL;
*/
    }// else if(bits == length)
    return bin;
}

int main(void){
    char *sbin = convertToBinary(8, 1);
    puts(sbin);
    free(sbin);

    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM