كيف يمكنني الحصول على قيمة عدد صحيح من شار في C ++؟
-
05-07-2019 - |
سؤال
وأود أن أغتنم القيمة المخزنة في صحيح غير الموقعة 32 بت، ووضعها في أربعة أحرف ومن ثم تخزين قيمة عددية لكل من هذه حرف في سلسلة.
وأعتقد أن الجزء الأول غني عن مثل هذا:
char a = orig << 8;
char b = orig << 8;
char c = orig << 8;
char d = orig << 8;
المحلول
إذا كنت تريد حقا أن استخراج البايتات الفردية أولا:
unsigned char a = orig & 0xff;
unsigned char b = (orig >> 8) & 0xff;
unsigned char c = (orig >> 16) & 0xff;
unsigned char d = (orig >> 24) & 0xff;
وأو:
unsigned char *chars = (unsigned char *)(&orig);
unsigned char a = chars[0];
unsigned char b = chars[1];
unsigned char c = chars[2];
unsigned char d = chars[3];
وأو استخدام الاتحاد من حرف غير موقعة طويلة وأربعة:
union charSplitter {
struct {
unsigned char a, b, c, d;
} charValues;
unsigned int intValue;
};
charSplitter splitter;
splitter.intValue = orig;
// splitter.charValues.a will give you first byte etc.
تحديث: كما أشار friol بها، حلول 2 و 3 ليست endianness-الملحد. التي بايت a
، b
، c
وd
تمثل تعتمد على بنية وحدة المعالجة المركزية.
نصائح أخرى
ودعونا نقول "الاصليه" هو متغير 32BIT والتي تحتوي على القيمة الخاصة بك.
وأنا تخيل أنك تريد أن تفعل شيئا من هذا القبيل:
unsigned char byte1=orig&0xff;
unsigned char byte2=(orig>>8)&0xff;
unsigned char byte3=(orig>>16)&0xff;
unsigned char byte4=(orig>>24)&0xff;
char myString[256];
sprintf(myString,"%x %x %x %x",byte1,byte2,byte3,byte4);
وأنا لست متأكد من أن هذا هو دائما endian الصحيح، بالمناسبة. (<م> تحرير م>: في الواقع، فمن endian صحيح، لأنه لا يجب أن تتأثر عمليات bitshift التي كتبها endianness)
وآمل أن يساعد هذا.
استخدم لunion
. (وبناء على طلب هنا هو نموذج البرنامج.)
#include <<iostream>>
#include <<stdio.h>>
using namespace std;
union myunion
{
struct chars
{
unsigned char d, c, b, a;
} mychars;
unsigned int myint;
};
int main(void)
{
myunion u;
u.myint = 0x41424344;
cout << "a = " << u.mychars.a << endl;
cout << "b = " << u.mychars.b << endl;
cout << "c = " << u.mychars.c << endl;
cout << "d = " << u.mychars.d << endl;
}
وكما ذكر جيمس هذا هو منصة محددة.
وليس تماما:
char a = orig & 0xff;
orig >>= 8;
char b = orig & 0xff;
orig >>= 8;
char c = orig & 0xff;
orig >>= 8;
char d = orig & 0xff;
ولست متأكدا ما تقصد ب "تخزين قيم عددية صحيحة من كل من هذه القيم إلى سلسلة بالضبط. هل تريد تحويل 0x10111213
إلى "16 17 18 19"
، أم ماذا؟
لعشري:
sprintf(buffer, "%lX", orig);
لالعشري:
sprintf(buffer, "%ld", orig);
استخدم snprintf
لتجنب تجاوز سعة المخزن المؤقت.