I'm running 2 programs that execute the same code : write to a binary file.
When the c++ code saves a one byte with value 2 to the file it seems to be binary stored as HEX 02. However when my C# program writes it to the file it seems to be stored as HEX 32.
Could it be this has something to do with char encoding UTF_16 is default in C#? (if I read correctly in an article a few days ago.)
Any way to make sure C# will write the byte value 2 to file as HEX 02 instead of HEX 32 ?
EndianBinaryWriter writer = new EndianBinaryWriter(new FileStream("myfile.dat", Endian.Little);
char LineDepth = '4';
if(MaxDev<=127) {
LineDepth = '1';
} else
if(MaxDev<=32767) {
LineDepth = '2';
}
// write line header
//char BlockBuf[5];
//MemoryStream BlockBuf = new MemoryStream();
//EndianBinaryWriter BlockBufWriter = new EndianBinaryWriter(endian, BlockBuf);
//hfzMemcpy(BlockBuf, &LineDepth, 1); // store line depth
//hfzMemcpy(BlockBuf+1, &FirstVal, 4); // store first value (32bit precis)
writer.Write(LineDepth);
This is a bit of an extract of the code but it should give the intention. I like to write away exactly one byte with value 1, 2 or 4 depending on some if statement. Now I always thought that a char was one byte so I'm trying to write it as a char but that seems to be wrong cause when I compare it with a file as how it SHOULD be it should be HEX 02 while in my file it's HEX 32
John showed me the light , by putting the byte value 2 from a source file into a char , I was not putting value 2 in that char but value 32 , which caused my resulting file to be corrupt. Kind of a rookie mistake, but maybe my question will help out other rookies in the future ?
You're writing the character '4', '1' or '2' - which is encoded in UTF-16 as 0x00 0x34 (etc).
It seems to me that you want to write a short
or ushort
value or 4, 1, or 2:
short lineDepth = 4;
if (MaxDev <= 127) {
lineDepth = 1;
} else
if (MaxDev <= 32767) {
lineDepth = 2;
}
writer.Write(lineDepth);
Note that's still writing two bytes. If you just want to write a single byte (your post and your comments seem to say different things), you want:
byte lineDepth = 4;
if (MaxDev <= 127) {
lineDepth = 1;
} else
if (MaxDev <= 32767) {
lineDepth = 2;
}
writer.Write(lineDepth);
It's very important that you understand the difference between 1 (an integer constant) and '1' (a character constant). You should try to avoid using text unless you're really trying to represent text.
Also note that "hex" is just one way of viewing the file. There's no such thing as a "hex entry" - there are just bytes. So the byte with a value of "sixteen" can be viewed as 16 (decimal) or 0x10 (hex). Those are two different ways of viewing the exact same content.
See more on this question at Stackoverflow