Skip to content

Instantly share code, notes, and snippets.

@bg1bgst333
Created July 8, 2024 00:57
Show Gist options
  • Save bg1bgst333/2f39876bd0f42d873962f289fd4c2a08 to your computer and use it in GitHub Desktop.
Save bg1bgst333/2f39876bd0f42d873962f289fd4c2a08 to your computer and use it in GitHub Desktop.
replace_byte#call_from_cpp
// ヘッダファイルのインクルード
extern "C"{ // C言語として解釈する.
#include "string_utility_cstring.h" // 文字列ユーティリティ(C文字列処理)
}
// main関数の定義
int main(){
// 配列の初期化.
char bytes[] = {0xa, 0xb, 0, 0xd, 0xe};
// バイト列で最初にみつかったバイトだけ置換.
int ret = replace_byte(bytes, 5, 0xd, 0);
for (int i = 0; i < 5; i++){
printf("bytes[%d] = 0x%x\n", i, bytes[i]);
}
printf("ret = %d\n", ret);
// プログラムの終了.
return 0;
}
/* ヘッダファイルのインクルード */
/* 独自のヘッダファイル */
#include "string_utility_cstring.h" /* 文字列ユーティリティ(C文字列処理) */
/* 長さsizeのバイト列bytesの最初にみつかったbeforeをafterに置換. */
int replace_byte(char *bytes, int size, char before, char after){
/* 変数の宣言 */
int i;
/* beforeがみつかるまで探す. */
for (i = 0; i < size; i++){
if (*(bytes + i) == before){
*(bytes + i) = after; /* afterに置換. */
return i; /* iを返す. */
}
}
/* みつからない場合は-1. */
return -1;
}
/* 二重インクルード防止 */
#ifndef __STRING_UTILITY_CSTRING_H__
#define __STRING_UTILITY_CSTRING_H__
/* ヘッダファイルのインクルード */
/* 既定のヘッダファイル */
#include <stdio.h> /* 標準入出力 */
#include <string.h> /* 文字列処理 */
/* 関数のプロトタイプ宣言 */
int replace_byte(char *bytes, int size, char before, char after); /* 関数replace_byteの宣言. */
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment