• 締切済み

H21年春期基本情報技術者午後問11(JAVA)

H21年春期基本情報技術者午後問11(JAVA)で、 [プログラム2]の 引数textに格納される物が分かりません。 分かる方、教えて下さい。 //プログラム1 class GapBuffer { private static final int INITIAL_GAP_SIZE = 128; private char[] buffer; private int gapOffset = 0; private int gapSize = INITIAL_GAP_SIZE; GapBuffer(String initialText){ buffer = new char[initialText.length() + gapSize]; System.arraycopy(initialText.toCharArray(), 0, buffer, gapSize, initialText.length()); } void insert(int offset, char ch) { confirmGap(offset); buffer[gapOffset++] = ch; gapSize--; } void delete(int offset){ if (length() == 0) return; confirmGap(offset + 1); gapOffset--; gapSize++; } char charAt(int offset) { if (offset >= gapOffset) offset += gapSize; return buffer[offset]; } int length() { return buffer.length - gapSize ;} private void confirmGap(int newGapOffset){ if (gapSize == 0) { char[] temp = new char[buffer.length + INITIAL_GAP_SIZE]; System.arraycopy(buffer, 0, temp, 0, buffer.length); gapOffset = buffer.length; gapSize = INITIAL_GAP_SIZE; buffer = temp; } if(newGapOffset < gapOffset) { System.arraycopy(buffer, newGapOffset, buffer, newGapOffset + gapSize, gapOffset - newGapOffset); } else { System.arraycopy(buffer, gapOffset + gapSize, buffer, gapOffset, newGapOffset - gapOffset); } gapOffset = newGapOffset; } } /プログラム2 class Editor { private GapBuffer buf; private int cursor = 0; private Editor(String text) { buf = new GapBuffer(text);←此処です } private void run() { Display.output(buf, cursor); char ch; while ((ch = CharReader.get()) != CharReader.EOF) { switch (ch){ case CharReader.MOVE_FORWARD: moveCursor(1); break; case CharReader.MOVE_BACKWARD: moveCursor(-1); break; case CharReader.DELITE: if (cursor < buf.length()) { buf.delete(cursor); } break; default: buf.insert(cursor++, ch); break; } Display.output(buf, cursor); } } private void moveCursor(int n) { int newCursor = cursor + n; if (newCursor >= 0 && newCursor <= buf.length()) { cursor = newCursor; } } public static void main(String[] args) { Editor editor = new Editor(args[0]); editor.run(); } }

みんなの回答

回答No.1

誰も来ませんね・・・。(たぶん、Javaカテだと、いろいろと相手をしてくださる方がいると思いますが。) いつもは一番手を控えているのですが、試験も直前ということもあり、今回は私が可能な範囲でアドバイス。 てっきり、Eclipseとかでコマンドライン引数を指定しての実行とかが分からないのかなと思っていたのですが、そうじゃなく、そもそもコンパイル自体が通りませんね。 問題文に書かれていた、「外部で与えられるクラス『CharReader』や『Display』」というのは、標準のクラスライブラリではなく、独自のクラス群です。 よって、import文をいくつか追加したらOKではなく(JDK5や6のAPIリファレンスにも載っていなかった)、独自にその2つのクラスを実装しないと、「ギャップバッファを利用した簡易テキストエディタ」のJavaプログラムをコンパイル・実行することは不可能でしょう。 この辺りに関しては、過去問とかで利用する人もいるんだし、ちゃんと全てのソースプログラムを載せといてよ、って思うんですが、逆に言うと、コードが冗長的で長くなることを避け、受験者への配慮も込めて、わざと必要な所のみ掲載したとも取れるのですが。(実際の所は、う~ん、どうなんだろう?) 雑談はさておき(論評にもなっていない、単なる独り言です、はい)、今回の質問へのアドバイスとしては、ずばり 「コンストラクタがいつ、どのように処理されているのか?」 がポイントですね。それぞれのクラスごとに、1つずつでオーバーロードされていませんし、すごくシンプルですね。 おあと、コマンドライン引数などに関しても分かり兼ねるようでしたら、以下の過去ログなんかも参考にしてみてください。 「public static void main (String args[])」 http://oshiete1.goo.ne.jp/qa1876924.html もし、クラス「CharReader」や「Display」を問題文の仕様通りにちゃんと実装し、コンパイルも通った後で、いざ実行となった場合、私なら以下のようにコマンド上から実行すると思います。 java Editor hogehoge

gookinger
質問者

お礼

ありがとうございました。

関連するQ&A

  • 春期の基本情報技術者試験の問題について

    基本情報試験の勉強の為に過去門を解いていたのですが 自分には分からない記述があったので質問しました 下記のプログラムの while(bp > base && *--bp != '/'); とは一体どのような処理をしているのか教えてください C言語は独学で勉強したのですがこのようなwhile文の 使用方法はどこにものっていなかったので・・・ よろしくお願いします。 問題は平成21年春期の基本情報技術者試験の 午後の問9です。 #include <string.h> void convert(const char*, const char*, char*); void convert(const char *path, const char *base, char *result){ const char *pp, *bp; char *rp; int length; /* pathが絶対パス表記の場合 */ if(*path == '/'){ ; return; } /* pathがカレントディレクトリの場合 */ if(!strcmp(path, ".") || !strcmp(path, "./")){ ; return; } length = strlen(base); bp = base + length; /* bpは文字列baseの終端を指す。*/ if(*(bp - 1) == '/') --bp; /* pathの先頭部にある".."又は"../"を解析することで, baseのパス表記のうち,どこまでresultと共通になるかを調べる。*/ for(pp = path; *pp != '\0' && *pp == '.';){ if(!strncmp(pp, "../", 3)){ pp += 3; while(bp > base && *--bp != '/'); }else if(!strncmp(pp, "./", 2)){ pp += 2; }else if(!strncmp(pp, "..\0", 3)){ pp += 2; while(bp > base && *--bp != '/'); }else{ break; } } /* baseのパス表記と共通な部分をresultに複写する。*/ length = ; strncpy(result, base, length); rp = ; *rp++ = '/'; /* pathの文字列のうち,先頭部分の"./"や".."を除いた残りの 部分(ppが指す文字列)を,resultの文字列に追加する。 */ strcpy(rp, pp); return; }

  • 22年度基本情報技術者試験の午後のプログラムの問題について

    22年度基本情報技術者試験の午後のプログラムの問題について 初めて受験しました。 結果は惨敗でした。 くやしくて、午後のプログラムの問題を家の環境(MicrosoftVisualC++2008ExpressEdition)で作ってみましたが、うまくいきません。 具体的には、linebufの中身がカタカナの「フ」の字がぎっしりつまってしまいます。 ソースは以下のようにしました。 #include <stdio.h> #define COLUMNS 80 /* 1行の最大文字数 */ void printout_text(char *); int main() { printf("VC++2008でプログラムを実行\n"); printout_text("file.txt"); return 0; } void printout_text(char *filename) { FILE *fp; char linebuf[COLUMNS + 1]; int ch, ch1, cpos = 0, gapp = -1, i; fp = fopen(filename, "r"); while ((ch = fgetc(fp)) != EOF) { switch(ch) { case '\n': linebuf[cpos] = '\0'; printf("%s\n", linebuf); cpos = 0; gapp = -1; break; case ' ': if (cpos <= COLUMNS) { linebuf[cpos] = '\0'; printf("%s\n", linebuf); cpos = 0; } gapp = cpos; linebuf[cpos++] = ch; break; default: if (cpos <= COLUMNS) { i = gapp + 1; ch1 = linebuf[i]; linebuf[i] = '\0'; printf("%s\n", linebuf); cpos = 0; if (i < COLUMNS) { linebuf[cpos ++] = ch1; i++; while (i < COLUMNS) { linebuf[cpos++] = linebuf[i++]; } } gapp = -1; } linebuf[cpos++] = ch; } } if (cpos > 0) { linebuf[cpos] = '\0'; printf("%s", linebuf); } fclose(fp); }

  • BNF→JAVA  基本問題らしいです

    学校の宿題でBNF→JAVAの課題が出て一応自分でやったんですが自身が無いので合ってるか見てください。 間違っていれば指摘お願いします。 特によくわからないのが繰り返し{}と省略可[]をどのようにしたらいいのかが迷いました。 問題 <B>::=[<DEC>]<S> <S>::="{"<S>"}"|<IF>|<WRITE> <IF>::="if"<E><S>";" <WRITE>::="int"<VAR>";"|"char"<VAR>";" 僕が考えた答え public void parseB(){ if parse Dec(); parseS(); } void parseS(){ if(tokenType==S_LBRACE)getToken(); while(tokenType==S_INT)parseS(); if(tokenType==S_RBRACE)getToken(); else if parseIf(); else if parseWrite(); elese error(); } void parseIf(){ if(tokenType==S_IF)getToken(); parseE(); parseS(); if(tokenType==S_SEMICOLON)getToken(); } void parseWrite(){ if(tokenType==S_INT)getToken(); parseVar(); if(tokenType==S_SEMICOLON)getToken(); parseVar(); if(tokenType==S_SEMICOLON)getToken(); }

  • C の文字列置き換え

    #include <stdio.h> // buffer overflowは無視している文字列置き換え関数 void replace(char *buf, char *pre, char *aft) {   char *p;   p = strstr(buf, pre);   if (p){     char *p_2 = p + strlen(pre);     replace(p_2, pre, aft);     memmove(p + strlen(aft), p_2, strlen(p_2)+1);     memcpy(p, aft, strlen(aft));   } } int main(void) {   char buf[1024] = "C:\\programfile\\LOG";   replace(buf, "LOG", "RESULT");   printf("%s\n", buf);   return 0; } というソースが以前出ていたのですがこのバッファーオーバフローはどうすれば回避できるのですか? お願いします

  • ソートプログラムの穴抜き問題がわからない!(明日試験:;)

    基数ソートプログラムの一部なんですが穴抜きでわからない部分がありまして・・。 栄小文字の文字列からなる単語データをアルファベット順に習える基数ソートなんですが、英数字が26種類あることから基数は27にしています。 *******; ↑ここの部分がわかりませんで:; #include <stdio.h> #define nmax 10000 #define length 5 int ch2int(char ch) { (略)// a~zを1~26に変換する。 } void scopy(char from[], char to[]) { int i = 0; while((to[i]=from[i])!='\0'){ i++ } } void radix_sort(char a[][length+1], int n) { int pos, order[27], i, j; char buf[nmax+1][length+1]; for(pos=length-1; pos>=0;pos--){ for(j=0;j<27;j++){ order[j]=0; } for(i=1;i<=n;i++){ *******; } for(j=1;j<27;j++){ *******; } for(i=n;i>=1;i--){ scopy(a[i], buf[order[ch2int(a[i][pos])]--]); } for(i=1; i<=n;i++){ *******; } } } int main() { int n=0;i,ch; charword[nmax+1][length+1]; printf("5文字以内で英単語を入力\n"); while(n<nmax){ i=0; while(i<length && (ch=getchar())!=EOF && ch!='\n' && ch!= ' '){ words[n+1][i++]=ch; } if(i>0){ while(i<length){ words[n+1][i++] = ' '; } words[n+1][length]='\0'; n++; } if(ch==EOF){ break; } } printf("\nソーティング前の入力データ\n"); for(i=1;i<=n;i++){ printf("words[%3d]=%s \n", i, words[i]); } radix_sort(words, n); printf("\nソーティング後のデータ\n"); for(i=1;i<=n;i++){ printf("words[%3d]=%s \n", i, words[i]); } } 長文で失礼ですが・・。どなたか教えていただければすっごい光栄です:;

  • C言語の関数の戻り値がおかしい?

    #include<stdio.h> #include<ctype.h> #include<stdlib.h> int get_word(char *buf,int buf_size,FILE *fp) { int len; int ch; while((ch = getc(fp)) != EOF && !isalnum(ch));/*→「英数字のとき」このループは飛ばす。*/ if(ch == EOF){/*もし英数字以外が入力されていたらメインプログラムにEOFを返す。*/ return EOF; } len = 0; do{ buf[len] = ch; len++; if(len >= buf_size){ fprintf(stderr,"word too long.\n"); exit(1); } }while((ch = getc(fp)) != EOF && isalnum(ch)); buf[len] = '\0'; return len; } int main(void) { char buf[256]; while(get_word(buf,256,stdin) != EOF){ printf("<<%s>>\n",buf); } return 0; } C言語ポインタ完全制覇という本のP67に載っていたプログラムをそのまま載せています。 get_word関数の中のif文で、EOFを返した時もループwhile(get_word(buf,256,stdin)により再入力するようなプログラムになっています。でも、「!=EOF」と記述されているのだから、EOFが返ったら終了だと思うのですが… なぜ再入力し続けるプログラム(無限ループ)になってしまっているのでしょうか? というか、私の環境で動作させたらおかしいだけじゃないでしょうか? よろしくお願いします。

  • C フォームから受け取った知をクッキーで発行 2

    前回 http://okwave.jp/qa/q7765400.html からあれこれしてフォームの値をクッキーに保存できるようになったのですが、バグが出てきました。 一、クッキーが存在しないとエラーが出る ニ、Deta1関数を使って文字列の分解を試みるもうまく分解されない この2つのバグを解決するにはどうしたら直せますか? ---以下ソース--- #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> char *nameset[2],*valueset[2]; char *nameset2[2],*valueset2[2]; int Deta1(char *a,int b); int Dcd(char *set,int a); void get_Form(void); void get_cookie(void); void set_cookie(void); int hen(char *buf, char *mae, char *ato); void Page(int mode); int main(void) { char *nameset[2],*valueset[2]; char *nameset2[2],*valueset2[2]; printf("Content-type: text/html\n"); get_Form(); set_cookie(); get_cookie(); printf("\n"); Page(0); } int Deta1(char *a,int b){ int i=0,cn=0; if(a[0]==NULL){ return(-1); } nameset[0]=a; while((a[++i]!=NULL)&&(i<b)){ /* 項目の分解 */ if(a[i]=='='){ a[i]=NULL; valueset[cn]=a+i+1; } /* データ項目で分解 */ else if(a[i]=='&'){ a[i]=NULL; cn++; nameset[cn]=a+i+1; } } return cn+1; } int Dcd(char *set,int a){ int i,j; char buf,*tmp; if(a==0){ return -1; } tmp=(char*)malloc(a); for(i=0,j=0;i<a;i++,j++){ if(set[i]=='+'){tmp[j]=' ';continue;} if(set[i]!='%'){tmp[j]=set[i];continue;} if(set[++i]>='A'){buf=set[i]-'A'+10;} else{buf=set[i]-'0';} buf*=16; if(set[++i]>='A'){buf+=set[i]-'A'+10;} else{buf+=set[i]-'0';} tmp[j]=buf; } for(i=0;i<j;i++){ set[i]=tmp[i]; } set[i]='\0'; free(tmp); return 0; } void get_Form(void){ int a=0; int i=0; char *chr=NULL; if ( getenv("CONTENT_LENGTH")!=NULL ){ a = atoi( getenv("CONTENT_LENGTH") ); } chr=(char *)malloc(a+1); scanf("%s",chr); chr[a] = '\0'; if (a==0){ return ; } int deta1=Deta1(chr,a); } void get_cookie(void){ int i=0,cn=0; int a=NULL; char *b; if( (getenv("HTTP_COOKIE"))!=NULL){ a=strlen(getenv("HTTP_COOKIE")); } if(a==NULL){ } b=getenv("HTTP_COOKIE"); while((b[++i]!=NULL)&&(i<a)){ if(b[i]=='='){ b[i]=NULL; nameset2[0]=b+i+1; } /* 項目の分解*/ if(b[i]=='-'){ b[i]=NULL; valueset2[cn]=b+i+1; } /*データ項目で分解*/ else if(b[i]=='&'){ b[i]=NULL; cn++; nameset2[cn]=b+i+1; } } for(i=0;i<cn+1;i++){ Dcd(nameset2[i],strlen(nameset2[i])); Dcd(valueset2[i],strlen(valueset2[i])); } } void set_cookie(void) { time_t timer; struct tm *tset; char expires[256]; char *name="sskchat"; int kikan=86400*90; char *set[2]; int i; for(i=0;i<2;i++){ set[i]=NULL; } for(i=0;i<2;i++){ set[i]=valueset[i]; } for(i=0;i<2;i++){ if(set[i]==NULL){ set[i]="no"; } } timer = time(NULL); timer += kikan; tset = gmtime(&timer); strftime(expires, 255, "%a, %d-%b-%Y %H:%M:%S GMT", tset); printf("Set-Cookie:%s=name-%s&mail-%s; expires=%s;\n",name,set[0],set[1],expires); } void Page(int mode){ FILE *fp; char *f1="!name!",*h1; char *f2="!mail!",*h2; if(valueset2[0]==NULL||strcmp("!name!",valueset2[0])==0){ h1=""; } else{ h1=valueset2[0]; } if(valueset2[1]==NULL||strcmp("!mail!",valueset2[1])==0){ h2=""; } else{ h2=valueset2[1]; } char buf[200]; char set[200]; fp = fopen("ren.html", "r+"); while( fgets( set, 200, fp ) != NULL ){ strcpy(buf,set); while(hen(buf, f1, h1)); while(hen(buf, f2, h2)); printf("%s", buf); } fclose(fp); } int hen(char *buf, char *mae, char *ato){ char *nw; size_t zen,go; zen = strlen(mae); go = strlen(ato); if(zen == 0 || (nw = strstr(buf, mae)) == NULL){ return 0; } memmove(nw + go, nw + zen, strlen(buf) - (nw + zen - buf ) + 1); memcpy(nw, ato, go); return 1; } ---ソースここまで--- ---ren.htmlの内容--- <form action="first.exe" method="post"> 名前:<input type="text" name="name" size="100" value="!name!"><br><br> メール:<input type="text" name="mail" size="100" value="!mail!"><br><br> 本文:<textarea name="text" cols="70" rows="10"></textarea><br><br> <input type="submit" value=" 送 信 "><br> </form>

    • ベストアンサー
    • CGI
  • 動かないです

    おかしなところが有ったらアドバイス・修正等お願いします。 うしろ3行を表示させたいです。 0~2行の場合はその分だけ表示させたいです。 # include <stdio.h> # include <stdlib.h> # include <string.h> char *getline(void) { char *buf = NULL; int size = 0; int oldsize; do { oldsize = size; size = size * 2 + 80; buf = realloc(buf, size + 1); if(!buf) { fprintf(stderr, "memory allocation failed\n"); exit(1); } if(!fgets(buf + oldsize, size + 1 - oldsize, stdin)) if(oldsize) break; else { free(buf); return NULL; } }while(strlen(buf + oldsize) == size - oldsize); return buf; } void scan(char **lines, int n_lines) { char *p; int i; for(i = 0; i < n_lines; i++) lines[i] = NULL; while(p = getline()) { free(lines[0]); for(i = 0; i < n_lines - 1; i++) lines[i] = lines[i+1]; lines[n_lines - 1] = p; } } void print(char **lines, int n_lines) { int i; for(i = 0; i < n_lines; i++) if(lines[i]) fputs(lines[i], stdout); } int main(void) { char *lines[3]; int i; scan(lines, 3); print(lines, 3); for(i = 0; i < 3; i++) free(lines[i]); return 0; }

  • global変数をブロック内から参照したい

    可変長配列の可変長配列を飲み込んで 吐き出すコードです global変数 *st_memory こいつをブロック内から参照するには どない書けば良いのでしょうか 構造体とか他の関数から引っぱり出しても 何故にかSegmentation faultで弾かれます mallocとかgotoの処理は無視して下さい _________________________ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #define MAX 256 typedef enum{ SUCCESS, EOF_FILE, MEM_OVER }Add_List; char *st_memory = NULL; //global void free_buffer(void){ free(st_memory); st_memory = NULL; } Add_List add_char(const int ch,int *count){ static int buffer = 0; assert(buffer >= *count); if(buffer == *count){ st_memory = (char *)realloc(st_memory, (buffer + MAX) * sizeof(char)); if(st_memory == NULL)return MEM_OVER; buffer += MAX; }// END if st_memory[*count] = ch; (*count)++; return SUCCESS; } // END add_char(const int,int); Add_List read_line(FILE *fp,char **line){ int ch,used_line = 0; Add_List status = SUCCESS; while((ch = getc(fp)) != EOF){ if(ch == '¥n'){ status = add_char('¥0',&used_line); if(status != SUCCESS)goto FUNK_END; break; } // END if status = add_char(ch,&used_line);// MAIN if(status != SUCCESS)goto FUNK_END; }// END while if(ch == EOF){ if(used_line > 0){ status = add_char('¥0',&used_line); if(status != SUCCESS)goto FUNK_END; }else{ status = EOF_FILE; goto FUNK_END; } // END if } // END if line[0] = (char *)malloc(sizeof(char) * used_line); if(line[0] == NULL){ status = MEM_OVER; goto FUNK_END; } strcpy(line[0],st_memory);// MAIN FUNK_END: if(status != SUCCESS)free_buffer(); return status; }// END read_line(FILE *,char **); char ** add_line(char **text_file,char *mem_line, int *line_alloc_num,int *line_num){ assert(*line_alloc_num >= *line_num); if(*line_alloc_num == *line_num){ text_file = (char **)realloc(text_file, (*line_alloc_num + MAX) * sizeof(char)); if(text_file == NULL)exit(0); *line_alloc_num += MAX; } // END if text_file[*line_num] = mem_line; (*line_num)++; return text_file; } // END add_line(char **,char *,int *,int *); char ** read_file(FILE *fp,int *line_p){ char **text_file = NULL; int line_alloc_num = 0; int line_num = 0; char *mem_line = NULL; while(read_line(fp,&mem_line) == 0){ text_file = add_line(text_file, mem_line,&line_alloc_num,&line_num); } // END while text_file = (char **)realloc(text_file, line_alloc_num * sizeof(char)); if(text_file == NULL)exit(0); *line_p = line_num; return text_file; } // END read_file((FILE *,int *); int main(void){ char **text = NULL; int i,line_num = 0; text = read_file(stdin,&line_num); printf("¥n"); for(i=0;i<line_num;i++) printf("%s¥n",text[i]); return 0; } ______________________

  • java

    Base64にエンコードしたものをデコードするプログラムです。(汎用性が低いのは仕様です)コンパイルは通ったのですが、実行したら以下のエラーが出てきました。 C:\Users\Owner\Documents\javadev>java Base64Decode2 hello.dat hello2.txt java.lang.ArrayIndexOutOfBoundsException: 97 at Base64Decode2.decode(Base64Decode2.java:51) at Base64Decode2.main(Base64Decode2.java:23) 指定の行を見ても原因がよく分かりません。とても初歩的な質問なのかもしれませんが、お願いします。 以下がプログラムコードです import java.io.*; public class Base64Decode2 { public static void main(String[] args) { // 変換テーブル char[] table = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'}; InputStream in = null; // 入力データ OutputStream out = null; // 出力先 try { in = new FileInputStream(args[0]); out = new FileOutputStream(args[1]); char[] cs; while ((cs=read4(in)) != null) { int[] buf = decode(cs, table);//ここが問題? for (int i=0; i<buf.length; i++) { System.out.print(buf[i]+", "); } System.out.println(); int[] buf2 = convert6to8(buf); write3(out, buf2); } } catch (Exception e) { e.printStackTrace(); // 例外の情報を表示する } finally { // in, out を閉じる try { in.close(); out.close(); } catch (Exception e) { } } } /** * 8ビットの2進数の列を復号化する. * @param cs * @param table 符号テーブル * @return */ public static int[] decode(char[] cs, char[] table) { int[] buf = new int[cs.length]; for (int i=0; i<buf.length; i++) { buf[i] = table[cs[i]];//ここが問題? } return buf; } public static int[] convert6to8(int[] buf) { String b; int[] buf2; if (buf.length == 2) { b = toBinary(buf[0], 6); buf2 = new int[1]; buf2[0] = fromBinary(b.substring(0, 8)); } else if (buf.length == 3) { b = toBinary(buf[0], 6) + toBinary(buf[1], 6); buf2 = new int[2]; buf2[0] = fromBinary(b.substring(0, 8)); buf2[1] = fromBinary(b.substring(8, 16)); } else { b = toBinary(buf[0], 6) + toBinary(buf[1], 6) + toBinary(buf[2], 6); buf2 = new int[3]; buf2[0] = fromBinary(b.substring(0, 8)); buf2[1] = fromBinary(b.substring(8, 16)); buf2[2] = fromBinary(b.substring(16, 24)); } return buf2; } /** * バイト列 bt の数を順に出力する. * @param bt 数の配列。長さは 3以下. 各数は8ビットの整数 */ public static void write3(OutputStream out, int[] bt) throws IOException { for (int i=0; i<3; i++) { if (i<bt.length) { out.write(bt[i]); } } } /** * in から文字を最大4つ読み出す. * @param in 入力ストリーム * @return 文字の配列。配列長は最大4. 入力終了したときには null を返す. */ public static char[] read4(InputStream in) throws IOException { char[] bs; int n0=in.read(); int n1=in.read(); int n2=in.read(); int n3=in.read(); if (n0 < 0) { // 読み込み終了 bs = null; } else if (n2 < 0 || (char) n2=='=') { bs = new char[2]; bs[0] = (char) n0; bs[1] = (char) n1; } else if (n3 < 0 || (char) n3=='=') { bs = new char[3]; bs[0] = (char) n0; bs[1] = (char) n1; bs[2] = (char) n2; } else { bs = new char[4]; bs[0] = (char) n0; bs[1] = (char) n1; bs[2] = (char) n2; bs[3] = (char) n3; } return bs; } /** * 数を読み取って、nビットの2進数を表す文字列に変換する * @param bt 1バイトの数 * @param n 2進数のビット数 * @return 2進数を表す文字列 */ public static String toBinary(int bt, int n) { String s = Integer.toBinaryString(bt); for (int i=s.length(); i<n; i++) { s = "0" + s; } return s; } /** * 2進数を表す文字列を数に変換する * @param b 2進数を表す文字列 * @return b が表す数 */ public static int fromBinary(String b) { return Integer.parseInt(b, 2); } }

    • ベストアンサー
    • Java

専門家に質問してみよう