C語言 str2bin 和 bin2str 實現

2022-03-31 08:14:47 字數 1499 閱讀 4731

在編碼或者除錯過程中經常需要進行 位元組碼轉換為 十六進製制的字串, 或者將 十六進製制字串 轉換為 位元組碼的需求。

即:  位元組碼 (記憶體中儲存的 01 串):    11111111

ff

linux上除錯通過。

#include

#include

#include

// stringify binary data. output buffer must be twice as big as input,

// because each byte takes 2 bytes in string representation

static void bin2str(char *to, const unsigned char *p, size_t len)

*to = '\0';

}unsigned char char2val(const char source)

}if ( !blegalchar )

if ( '0' <= source && source <='9'  )

else if ( 'a' <= source && source <= 'f' )

else

}// translate hex string to dest bin buff, which is len in length

static void str2bin(const char* source, unsigned char * dest, size_t len)

hex = source;

while ( *(hex) )

else}}

#define byte unsigned char

#define default_val (unsigned long)-1

void main()

;char binstr2[1024] = ;

printf("aaaa\n");

byte buff[4] = ;

byte buff2[4] = ;

memset(buff, -1, 4);

bin2str(binstr, buff, 4);

printf("buff binstr =%s\n", binstr );

str2bin(binstr, buff2, 4);

bin2str(binstr2, buff2, 4);

printf("buff2 binstr2 =%s\n", binstr2);

printf("bbbb\n");

}

**演示了, 將乙個 4 byte的空間, 初始化為 –1 , 即全部bit位置設定為 1, 然後將此空間轉換為 hex字串,

然後再將此hex字串轉換為 byte位元組碼空間。

C 字串 int轉換 bin2int CRC

字串轉int型別 include include intmy atoi char pstr while isspace pstr 符號是正號,指標指向下乙個字元 負號,integer sign置為 1,指標指向下乙個字元 if pstr if pstr pstr while pstr 0 pstr ...

C語言程式設計(練習2 陣列和指標)

題目 編寫程式,把下面的資料輸入乙個二維陣列中。25 36 78 13 12 26 88 93 75 18 22 32 56 44 36 58 然後執行以下操作 輸出矩陣兩個對角線上的數 分別輸出各行和各列的和 交換第一行和第三行的位置 交換第二列和第四列的位置 輸出處理後的陣列 實現 編寫程式,把...

C語言中的atan和atan2

在c語言的math.h或c 中的cmath中有兩個求反正切的函式atan double x 與atan2 double y,double x 他們返回的值是弧度 要轉化為角度再自己處理下。前者接受的是乙個正切值 直線的斜率 得到夾角,但是由於正切的規律性本可以有兩個角度的但它卻只返回乙個,因為ata...