Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read a byte and save ASCII value of byte in integer in c++

Tags:

c++

char

int

ascii

I have a simple question that is confusing me.

Goal: I want to read a given byte from a file (say the first byte) and make int x with the ASCII value of that byte. So, for example, if the byte/character is 'a', I want x to be 97 (= 61 in hex). I have the following reading the first byte of the file example.txt:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main(){
  unsigned int x;
  unsigned char b;
  ifstream myFile ("example.txt", ios::out | ios::binary);
  myFile.seekg (0, ios::beg);
  myFile >> b;
  x = (unsigned int)b;
  cout << hex << x;
  return b;
}

Problem: If the first byte is represented by 08, then indeed I get an output of 8. But if the byte is represented by 09, then I get 0. I have noticed that I seem to get the following byte unless that byte is also 09. I don't know if my problem is only when the byte is represented in ASCII by 09.

Question: So how to I read say the first (or third or whatever) byte from a file and make an int with the ASCII value of that byte?

(I am on Windows XP)

like image 829
Thomas Avatar asked Mar 03 '12 01:03

Thomas


People also ask

Is ASCII code an integer?

In C programming, a character variable holds ASCII value (an integer number between 0 and 127) rather than that character itself. This integer value is the ASCII code of the character. For example, the ASCII value of 'A' is 65.

Is a char a byte in C?

char is 1 byte in C because it is specified so in standards. The most probable logic is. the (binary) representation of a char (in standard character set) can fit into 1 byte.

How many bytes to store a string in C?

A string is composed of: An 8-byte object header (4-byte SyncBlock and a 4-byte type descriptor)


1 Answers

This should fix it.

 myFile >> noskipws >> b;
like image 82
Mark H Avatar answered Sep 28 '22 23:09

Mark H