Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

reading chars and ints in bytes : confusion

 
rijagu chan
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In a file how do you read chars and ints in terms of bytes:
for example :
String a = "abcd" is 4 bytes
int b = 12345 is 1 byte

i don't understand how. Could you please explain.
Thanks and Kudos to all of you.
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I dont understand. How does int have one byte ? .
In java an int takes up 4 bytes and a character takes up 2 bytes.
 
rijagu chan
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
sorry for the confusion:
Lets write to a file the following:
WriteBoolean(false);
writeInt(123456);
writeInt(8670);
file.seek(5);
System.out.println(readInt());
answer is 8670
please explain
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the file the information will be as follows
byte-0 byte-1 byte-2 byte-3 byte-4 byte5 byte6 byte7 byte8
false <------123456 ------------> <-----8670------------>
call to seek(5) will position the file pointer right before 8670, so that the readInt() returns 8670.
I am making any sense ?
- srini
 
Uvnik Gupta
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
WriteBoolean(false): writes 1 byte
writeInt(123456) : writes 4 Bytes
writeInt(8670) : writes 4 bytes
file.seek(5) : seeks to the 5th byte and since all read/write indexes start from 0 seek(5) points to the 6 position ie starting of 8670.
System.out.println(readInt()) : Reads 4 bytes and prints 8670.
Hope it's clear.
 
rijagu chan
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Perfect. Clear and makes sense, thanks a lot.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic