類似於repalce的位的替換

來源:互聯網
上載者:User

題目:就是實現位的替換

原型:void append(unsigned char *s,int n,unsigned char *buf,int len)

說明:s為目標字串,n為位元,buf為緩衝區,len為buf的長度。
現在要在s中的第n位開始,賦上buf的值。
不能用動態記憶體分配函數。
求解答。

注意,我說的是位。。。。不是位元組。。相當於是s中的第n位到第n+len位是buf的len位。

題目來自:http://topic.csdn.net/u/20111108/12/8eb961d4-7d35-4193-9ed4-ff3e71ca140e.html?85604

實現方法:

#include <stdio.h>void append(unsigned char *s,int n,unsigned char *buf,int len);void printa(unsigned char *a, int a_len);int main(int argc, char *argv[]){unsigned char s[2] = {0x12,0x34};unsigned char buf[2] = {0x45,0x56};printa(s, sizeof(s));printa(buf, sizeof(buf));append(s, 2, buf, 3);printa(s, sizeof(s));printa(buf, sizeof(buf));return 0;}void append(unsigned char *s,int n,unsigned char *buf,int len){unsigned char bits[8] = {0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01};int i;for(i=0; i<len; ++i) {int x = i+n-1;if((*(buf+i/8)) & bits[i%8]) {*(s+x/8) |= bits[x%8];} else {*(s+x/8) &= ~bits[x%8];}}return;}void printa(unsigned char *a, int a_len){int i;for(i=0; i<a_len; ++i) {printf("%02X ", a[i]);}printf("\n");return;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.